def time_test(fn, n, t):
duraton = []
avg = 0
for i in range(t):
start = time.time() # time模块里的time方法,可以获取当前时间的时间戳
fn(n) # fn传过来函数名,加()调用此函数
end = time.time() # 记录程序结束时间
duration.append(end - start)
avg += duration[i]/t
return avg
fn
is the function you are testing, n
is the argument and t
is the number of times to average the result.
And there is this shortcut I made.
def T(fn,n,t):
return dict(zip(fn,[time_test(f, n, t) for f in fn]))
Where fn
is, instead of one function, many functions stored in a list.
There are many ways to find the factorial.
from math import factorial as math_
def recurse(n):
if n == 1:
return 1
else:
return n*recurse(n-1)
def for_(n):
s = 1
for i in range(1,n+1):
s *= i
return s
def while_1(n):
s=1
i=1
while i in range(1,n+1):
s*=i
i+=1
return s
def while_2(n):
s=1
i=1
while i<=n:
s*=i
i+=1
return s
from functools import reduce as R
def reduce(n):
return int(R(lambda x,y:x*y, list(range(1,n+1))))
print(T([math_,recurse,for_,while_1,while_2,reduce],100,10000))
{<built-in function factorial>: 1.1588335037231e-06, <function recurse at 0x1071ab3a0>: 2.058548927306996e-05, <function for_ at 0x10730b3a0>: 6.616473197938017e-06, <function while_1 at 0x10730b430>: 3.170087337494361e-05, <function while_2 at 0x10730b4c0>: 9.050393104552102e-06, <function reduce at 0x10730b550>: 1.2172722816468491e-05}