Skip to content

Instantly share code, notes, and snippets.

@lukewendling
Created July 21, 2016 17:51
Show Gist options
  • Save lukewendling/c4d406981da7aee7fae75f3c23aad402 to your computer and use it in GitHub Desktop.
Save lukewendling/c4d406981da7aee7fae75f3c23aad402 to your computer and use it in GitHub Desktop.
https://repl.it/Ce6k/1 created by lukewendling
from multiprocessing import Process
import os
import time
PRIMES_MAX = 10000000
def primes(n):
# info('primes')
if n==2:
return [2]
elif n<2:
return []
s=range(3,n+1,2)
mroot = n ** 0.5
half=(n+1)/2-1
i=0
m=3
while m <= mroot:
if s[i]:
j=(m*m-3)/2
s[j]=0
while j<half:
s[j]=0
j+=m
i=i+1
m=2*i+3
return [2]+[x for x in s if x]
class Timer(object):
def __init__(self, verbose=False):
self.verbose = verbose
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # millisecs
if self.verbose:
print 'elapsed time: %f ms' % self.msecs
# Parallel
with Timer() as t:
for i in range(5):
p = Process(target=primes, args=(PRIMES_MAX,))
p.start()
p.join()
print "=> parallel elapsed time: %s s" % t.secs
# Serial
with Timer() as t:
for i in range(5):
primes(PRIMES_MAX)
print "=> serial elapsed time: %s s" % t.secs
def info(title):
print title
print 'module name:', __name__
if hasattr(os, 'getppid'): # only available on Unix
print 'parent process:', os.getppid()
print 'process id:', os.getpid()
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
>>> => parallel elapsed time: 7.55565905571 s
=> serial elapsed time: 10.0534369946 s
=> None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment