把写代码过程中比较重要的代码片段珍藏起来,下边资料是关于Fast Prime List Functions的代码。
'''primelist_timing1.py
timing some very fast primelist functions
tested with Python27 and Python32 by vegaseat
'''
import timeit
import numpy
import sys
print("Python version:n %sn" % sys.version)
def time_function(stmt, setup):
"""
use module timeit to time functions
"""
# to enable garbage collection start setup with 'gc.enable();'
#setup = 'gc.enable();' + setup
t = timeit.Timer(stmt, setup)
times = 10000
num = 100
# (lower num is a little less precise but saves time)
print("%-20s --> %0.2f microseconds/pass" % (stmt, elapsed))
def primelist_bw(n):
"""
returns a list of primes < n
by Bill Woods
"""
if sieve[x>>1]:
return [2] + [(x<<1)+1 for x in range(1, n>>1) if sieve[x]]
def primelist_ds(n):
"""
returns a list of primes < n
"""
if sieve[x>>1]:
return [2] + [(x<<1)+1 for x in range(1, n>>1) if sieve[x]]
def primes_numpy(n):
"""
requires module numpy and n>=6,
returns a list of primes 2 <= p < n
"""
sieve[0] = False
if sieve[x]:
# time a function
stmt = 'primelist_bw(1000000)'
setup = 'from __main__ import primelist_bw'
time_function(stmt, setup)
# time a function
stmt = 'primelist_ds(1000000)'
setup = 'from __main__ import primelist_ds'
time_function(stmt, setup)
# time a function
stmt = 'primes_numpy(1000000)'
setup = 'from __main__ import primes_numpy, numpy'
time_function(stmt, setup)
# additional test (show the last 5 primes) ...
print(primelist_bw(1000000)[-5:])
print(primelist_ds(1000000)[-5:])
print(primes_numpy(1000000)[-5:])
'''result ...
Python version:
2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
primelist_bw(1000000) --> 75969.22 microseconds/pass
primelist_ds(1000000) --> 73669.90 microseconds/pass
primes_numpy(1000000) --> 9016.74 microseconds/pass
------------------------------------------------------------
[999953, 999959, 999961, 999979, 999983]
[999953, 999959, 999961, 999979, 999983]
[999953, 999959, 999961, 999979, 999983]
Python version:
3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
primelist_bw(1000000) --> 77284.28 microseconds/pass
primelist_ds(1000000) --> 75547.38 microseconds/pass
primes_numpy(1000000) --> 28055.11 microseconds/pass
------------------------------------------------------------
[999953, 999959, 999961, 999979, 999983]
[999953, 999959, 999961, 999979, 999983]
[999953, 999959, 999961, 999979, 999983]
'''