|
# Time a function using time. time () and the @ function decorator
# Tested with Python24 vegaseat 21aug2005
Import time
Def print_timing (func ):
Def wrapper (* arg ):
T1 = time. time ()
Res = func (* arg)
T2 = time. time ()
Print '% s took % 0.3f ms' % (func. func_name, (t2-t1) * 1000.0)
Return res
Return wrapper
# Declare the @ decorator just before the function, invokes print_timing ()
@ Print_timing
Def getPrimeList (n ):
"Returns a list of prime numbers from 2 to <n using a sieve algorithm """
If n <2: return []
If n = 2: return [2]
# Do only odd numbers starting at 3
S = range (3, n + 1, 2)
# N * 0.5 may be slightly faster than math. sqrt (n)
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
S [j] = 0
J + = m
I = I + 1
M = 2 * I + 3
Return [2] + [x for x in s if x]
If _ name _ = "_ main __":
Print "prime numbers from 2 to <10,000,000 using a sieve algorithm"
PrimeList = getPrimeList (10000000)
Time. sleep (2.5)
"""
My output -->
Prime numbers from 2 to <10,000,000 using a sieve algorithm
GetPrimeList took 4750.000 MS
"""
|