Remarkable results with psyco and sieve of Eratosthenes

George Sakkis george.sakkis at gmail.com
Wed Nov 29 20:15:03 EST 2006


Will McGugan wrote:
> > #!/usr/bin/python -OO
> > import math
> > import sys
> > import psyco
> >
> > psyco.full()
> >
> > def primes():
> >     primes=[3]
> >     for x in xrange(5,10000000,2):
> >         maxfact = int(math.sqrt(x))
> >         flag=True
> >         for y in primes:
> >             if y > maxfact:
> >                 break
> >             if x%y == 0:
> >                 flag=False
> >                 break
> >         if flag == True:
> >             primes.append(x)
> > primes()
> >
>
> Some trivial optimizations. Give this a whirl.
>
> def primes():
>      sqrt=math.sqrt
>      primes=[3]
>      for x in xrange(5,10000000,2):
>          maxfact = int(sqrt(x))
>          for y in primes:
>              if y > maxfact:
>                  primes.append(x)
>                  break
>              if not x%y:
>                  break
>      return primes

You can also save an attribute lookup for append; just add
append = primes.append
outside of the loop and replace primes.append(x) with append(x)
That should cut down a few fractions of second.

George




More information about the Python-list mailing list