Skip to content

Commit d533eb0

Browse files
committed
Add comparison between cythonized and pure Python
1 parent b09f5af commit d533eb0

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/env python
2+
3+
from argparse import ArgumentParser
4+
import numpy as np
5+
import pyximport
6+
import timeit
7+
8+
pyximport.install(pyimport=True)
9+
import array_sum_pure
10+
11+
def py_sum(a):
12+
total = 0.0
13+
for i in range(a.shape[0]):
14+
for j in range(a.shape[1]):
15+
total += a[i, j]
16+
return total
17+
18+
if __name__ == '__main__':
19+
arg_parser = ArgumentParser(description='compute array sum using '
20+
'pure, non-cythonized and pure cythonized implementations')
21+
arg_parser.add_argument('--n', type=int, default=10_000,
22+
help='size (nxn array)')
23+
arg_parser.add_argument('--iter', type=int, default=10,
24+
help='number of iterations')
25+
options = arg_parser.parse_args()
26+
a = np.ones((options.n, options.n))
27+
for func in [array_sum_pure.array_sum, py_sum]:
28+
total = 0.0
29+
start_time = timeit.default_timer()
30+
for iter_nr in range(options.iter):
31+
total += func(a)
32+
total_time = timeit.default_timer() - start_time
33+
print(f'{func.__qualname__:s}: {total_time:.6f} s ({total})')
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/usr/bin/env python
2+
3+
from argparse import ArgumentParser
4+
import array_sum_pure
5+
import numpy as np
6+
import timeit
7+
8+
def py_sum(a):
9+
total = 0.0
10+
for i in range(a.shape[0]):
11+
for j in range(a.shape[1]):
12+
total += a[i, j]
13+
return total
14+
15+
if __name__ == '__main__':
16+
arg_parser = ArgumentParser(description='compute array sum using '
17+
'pure, non-cythonized and pure cythonized implementations')
18+
arg_parser.add_argument('--n', type=int, default=10_000,
19+
help='size (nxn array)')
20+
arg_parser.add_argument('--iter', type=int, default=10,
21+
help='number of iterations')
22+
options = arg_parser.parse_args()
23+
a = np.ones((options.n, options.n))
24+
for func in [array_sum_pure.array_sum, py_sum]:
25+
total = 0.0
26+
start_time = timeit.default_timer()
27+
for iter_nr in range(options.iter):
28+
total += func(a)
29+
total_time = timeit.default_timer() - start_time
30+
print(f'{func.__qualname__:s}: {total_time:.6f} s ({total})')

0 commit comments

Comments
 (0)