Speed up this code?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri May 26 16:57:27 EDT 2006


I have tried this comparison, with a version I've modified a bit, I
have encoutered a problem in sieve_all, for example with n=10000, I
don't know why:

def sieve_all(n=100):
    # yield all primes up to n
    stream = iter(xrange(2, n))
    while True:
        p = stream.next()
        yield p
        def s1(p, stream):
            # yield all non-multiple of p
            return (q for q in stream if q%p != 0)
        stream = s1(p, stream)


def primes(n):
    "primes(n): return a list of prime numbers <=n."
    # Recipe 366178 modified and fixed
    if n == 2:
        return [2]
    elif n<2:
        return []
    s = range(3, n+2, 2)
    mroot = n ** 0.5
    half = len(s)
    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 += 1
        m = 2 * i + 3
    if s[-1] > n:
        s[-1] = 0
    return [2] + filter(None, s)



from time import clock
pmax = 21

for p in xrange(12, pmax):
    n = 2 ** p
    t1 = clock()
    primes(n)
    t2 = clock()
    list(sieve_all(n))
    t3 = clock()
    print "primes(2^%s= %s):" % (p, n), round(t2-t1, 3), "s",
round(t3-t2, 3), "s"

import psyco
psyco.bind(primes)
psyco.bind(sieve_all)

for p in xrange(12, pmax):
    n = 2 ** p
    t1 = clock()
    primes(n)
    t2 = clock()
    list(sieve_all(n))
    t3 = clock()
    print "primes(2^%s= %s):" % (p, n), round(t2-t1, 3), "s",
round(t3-t2, 3), "s"


Bye,
bearophile




More information about the Python-list mailing list