Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of concurrent processusing Python builtin library(example modified from example in Python docs)
#!/usr/bin/env python
import os
from concurrent.futures import ProcessPoolExecutor
import math
import time
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
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 time_taken(func):
def wrapper():
start = time.time()
func()
stop = time.time()
return (stop - start)
return wrapper
@time_taken
def main():
with ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
@time_taken
def main2():
for number in PRIMES:
prime = is_prime(number)
print('%d is prime: %s' % (number, prime))
if __name__ == '__main__':
start = time.time()
span1 = main()
span2 = main2()
print('1st: %.4f' % span1)
print('2nd: %.4f' % span2)
pct_savings = (span2 - span1) / span2
print('SAVING: %.3f' % (pct_savings * 100))
print('CPU count: %d' % os.cpu_count())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment