summaryrefslogtreecommitdiff
path: root/primes.py
diff options
context:
space:
mode:
authorAlex Gr?nholm <alex.gronholm@nextday.fi>2010-12-18 06:01:09 +0000
committerAlex Gr?nholm <alex.gronholm@nextday.fi>2010-12-18 06:01:09 +0000
commit3eb85180cce06b3cfc3cc6e75ba97bd0bbed23f3 (patch)
tree3a8beeebe683fff8cf64ac87c89b2dbed595ca54 /primes.py
parent635b1f0d5bb08ed01a71fcfd146816db87da495e (diff)
downloadfutures-3eb85180cce06b3cfc3cc6e75ba97bd0bbed23f3.tar.gz
Moved the code in the futures package to concurrent.futures as per PEP 3148; unified the codebase to support both Python 2 and 3 in a single tree; added support to Python 2.5; added tox.ini for easy testing with multiple Python versions
Diffstat (limited to 'primes.py')
-rw-r--r--primes.py50
1 files changed, 50 insertions, 0 deletions
diff --git a/primes.py b/primes.py
new file mode 100644
index 0000000..0da2b3e
--- /dev/null
+++ b/primes.py
@@ -0,0 +1,50 @@
+from __future__ import with_statement
+import math
+import time
+import sys
+
+from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
+
+PRIMES = [
+ 112272535095293,
+ 112582705942171,
+ 112272535095293,
+ 115280095190773,
+ 115797848077099,
+ 117450548693743,
+ 993960000099397]
+
+def is_prime(n):
+ if n % 2 == 0:
+ return False
+
+ sqrt_n = int(math.floor(math.sqrt(n)))
+ for i in range(3, sqrt_n + 1, 2):
+ if n % i == 0:
+ return False
+ return True
+
+def sequential():
+ return list(map(is_prime, PRIMES))
+
+def with_process_pool_executor():
+ with ProcessPoolExecutor(10) as executor:
+ return list(executor.map(is_prime, PRIMES))
+
+def with_thread_pool_executor():
+ with ThreadPoolExecutor(10) as executor:
+ return list(executor.map(is_prime, PRIMES))
+
+def main():
+ for name, fn in [('sequential', sequential),
+ ('processes', with_process_pool_executor),
+ ('threads', with_thread_pool_executor)]:
+ sys.stdout.write('%s: ' % name.ljust(12))
+ start = time.time()
+ if fn() != [True] * len(PRIMES):
+ sys.stdout.write('failed\n')
+ else:
+ sys.stdout.write('%.2f seconds\n' % (time.time() - start))
+
+if __name__ == '__main__':
+ main()