git » pymisc » master » tree

[master] / samples / pfunctional / sample1.py

import sys
import threading
import time

from pfunctional import pmap, pfilter

#
# pmap()
#

def fm(e):
	tid = threading.currentThread()
	print tid, 'p', e
	time.sleep(0.1)
	print tid, 'd', e
	return -e


#
# pfilter()
#

def ff(e):
	tid = threading.currentThread()
	print tid, 'p', e
	time.sleep(0.1)
	print tid, 'd', e
	if e > 100: return True
	return False


#
# main
#

# with one thread this would take 20 seconds, with two threads, 10 seconds,
# with 4 threads, 5 seconds
if __name__ == '__main__':
	if len(sys.argv) < 2 or sys.argv[1] not in ['map', 'filter']:
		print "Use: ptest.py [map|filter]"
		sys.exit(1)
	arg = sys.argv[1]
	if arg == 'map':
		r = pmap(fm, range(200), workers = 4)
	elif arg == 'filter':
		r = pfilter(ff, range(200), workers = 4)

	print list(r)