Skip to content

Instantly share code, notes, and snippets.

@shisashi
Created July 9, 2012 13:41
Show Gist options
  • Save shisashi/3076649 to your computer and use it in GitHub Desktop.
Save shisashi/3076649 to your computer and use it in GitHub Desktop.
#! /usr/bin/env /python
# -*- coding: utf-8 -*-
from itertools import ifilter, islice
def gen_odd():
n = 3
while True:
yield n
n += 2
def primes1():
yield 2
g = gen_odd()
while True:
prime = g.next()
yield prime
g = ifilter(lambda x, prime = prime: x % prime, g)
def primes3():
yield 2
g = gen_odd()
while True:
prime = g.next()
s_prime = prime * prime
ps = []
while s_prime != prime:
yield prime
ps.append(prime)
prime = g.next()
pred = lambda x, ps = ps: all(x % p for p in ps)
g = ifilter(pred, g)
def bench():
from timeit import Timer
import timeit
timeit.__dict__.update(p1 = primes1)
timeit.__dict__.update(p3 = primes3)
stmt = 'for p in g: pass'
setup1 = 'g = itertools.islice(p1(), MAX)'
setup3 = 'g = itertools.islice(p3(), MAX)'
for n in (100, 1000, 10000):
timeit.__dict__.update(MAX = n)
print 'take %d primes: %f : %f' % (n, Timer(stmt, setup1).timeit(1), Timer(stmt, setup3).timeit(1))
def test():
MAX = 1000
p1 = [p for p in islice(primes1(), MAX)]
p3 = [p for p in islice(primes3(), MAX)]
print p1 == p3, len(p1), len(p3)
if __name__ == u'__main__':
#test()
bench()
take 100 primes: 0.001078 : 0.000558
take 1000 primes: 0.098870 : 0.008400
take 10000 primes: 9.724632 : 1.687156
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment