- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry_in_python.py
More file actions
Latest commit
61 lines (41 loc) · 1.28 KB
/
Copy pathtry_in_python.py
File metadata and controls
61 lines (41 loc) · 1.28 KB
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
importsys
importtimeit
sys.path.append("./target/release")
fromlibrust_python_exampleimportfibasrust_fib
defpython_fib(fib_num):
iffib_num<2:
return1
prev1=1
prev2=1
new=0
foriinxrange(fib_num):
new=prev1+prev2
prev2=prev1
prev1=new
returnprev1
# make sure both perform the fib function correctly
num=30
rust_res=rust_fib(num)
print("rust fib({0}) = {1}".format(num, rust_res))
python_res=python_fib(num)
print("python fib({0}) = {1}".format(num, python_res))
# use timeit to measure the performance of both
iterations=100000
rust_total_time=timeit.timeit('rust_fib({0})'.format(
num), setup="""
from __main__ import rust_fib
gc.enable()
""", number=iterations)
rust_average_time=rust_total_time/iterations
python_total_time=timeit.timeit('python_fib({0})'.format(
num), setup="""
from __main__ import python_fib
gc.enable()
""", number=iterations)
python_average_time=python_total_time/iterations
# print results from benchmark
print("rust fib({0}) average time: {1}".format(num, rust_average_time))
print("python fib({0}) average time: {1}".format(num, python_average_time))
print("rust speedup factor = {0}".format(
python_average_time/rust_average_time))
print("Done!")