-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbench_factorial.py
80 lines (58 loc) · 1.83 KB
/
bench_factorial.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import timeit
from functools import reduce
from operator import mul
from cocode import *
def factorial_asm(value):
pass
factorial_asm_proxy = CodeObjectProxy(
VariableFast("value"),
Dup(),
Label(Constant(1), "loop"),
Sub(),
Dup(),
Rot3(),
Mult(),
Rot2(),
Dup(),
Constant(1),
Compare("=="),
PopJumpFalse("loop"),
Pop(),
Return(),
interface=factorial_asm,
)
fac_asm_code = factorial_asm_proxy.assemble()
factorial_asm.__code__ = fac_asm_code
assert factorial_asm(10) == 3628800, "ASM code works, but the result is wrong."
def factorial_recursive(value):
return 1 if value == 1 else factorial_recursive(value - 1) * value
def factorial_forloop(value):
result = 1
for i in range(1, value + 1):
result *= i
return result
def factorial_whileloop(value):
result = 1
while value > 1:
result *= value
value -= 1
return result
factorial_reduce = lambda value: reduce(mul, range(1, value + 1), 1)
rlambda = (
lambda func: lambda value: func(func, value)
)(
lambda fac, value: 1 if not value else fac(fac, value - 1) * value
)
if __name__ == "__main__":
print("Benching factorial asm...")
print(timeit.timeit(lambda: factorial_asm(900), number=10000))
print("Benching factorial recursive...")
print(timeit.timeit(lambda: factorial_recursive(900), number=10000))
print("Benching factorial recursive lambda...")
print(timeit.timeit(lambda: rlambda(900), number=10000))
print("Benching factorial for loop...")
print(timeit.timeit(lambda: factorial_forloop(900), number=10000))
print("Benching factorial while loop...")
print(timeit.timeit(lambda: factorial_whileloop(900), number=10000))
print("Benching factorial reduce...")
print(timeit.timeit(lambda: factorial_reduce(900), number=10000))