usr bin env python import time import operator def fact if return ret

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python
import time
import operator
def fact(x):
if x == 0: return 1
ret = x
while x > 1:
x -= 1
ret *= x
return ret
def fact_r(x): return reduce(operator.mul, xrange(2, x+1))
def fact_l(x): return reduce(lambda x, y: x*y, xrange(2, x+1))
def time_perf(x, func, count=500):
start = time.time()
for i in xrange(count):
func(x)
end = time.time()
return (end - start) / count
print "Fact simple"
print time_perf(500, fact)
print "Fact reduce"
print time_perf(500, fact_r)
print "Fact lambda"
print time_perf(500, fact_l)