Skip to content

Commit 7d17ec4

Browse files
committed
Simplify code
1 parent 60afc9c commit 7d17ec4

File tree

3 files changed

+9
-13
lines changed

3 files changed

+9
-13
lines changed

source-code/cython/Numpy/array_init.pyx

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
from functools import reduce
21
import numpy as np
32

43

54
def cons(dims):
6-
array = np.empty(reduce(lambda x, y: x*y, dims, 1))
5+
array = np.empty(np.prod(dims))
76
_cons(memoryview(array))
87
return array.reshape(dims)
98

source-code/cython/Numpy/array_sum.pyx

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,14 @@ from cython cimport boundscheck, wraparound
22

33

44
def array_sum(a):
5-
return _array_sum(memoryview(a))
5+
return _array_sum(memoryview(a.reshape((-1, ))))
66

77

8-
cdef double _array_sum(double[:,::1] mem_view):
8+
cdef double _array_sum(double[:] mem_view):
99
cdef double total = 0.0
1010
cdef m = mem_view.shape[0]
11-
cdef n = mem_view.shape[1]
12-
cdef int i, j
11+
cdef int i
1312
with boundscheck(False), wraparound(False):
1413
for i in range(m):
15-
for j in range(n):
16-
total += mem_view[i, j]
14+
total += mem_view[i]
1715
return total
Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
#!/usr/bin/env python
22

33
from argparse import ArgumentParser
4+
import array_sum
45
import numpy as np
56
import timeit
6-
from array_sum import array_sum
77

88

99
def py_sum(a):
@@ -16,17 +16,16 @@ def py_sum(a):
1616
if __name__ == '__main__':
1717
arg_parser = ArgumentParser(description='compute array sum using '
1818
'np.sum, cython and python')
19-
arg_parser.add_argument('--n', type=int, default=10000,
19+
arg_parser.add_argument('--n', type=int, default=10_000,
2020
help='size (nxn array)')
2121
arg_parser.add_argument('--iter', type=int, default=10,
2222
help='number of iterations')
2323
options = arg_parser.parse_args()
2424
a = np.ones((options.n, options.n))
25-
for func in [array_sum, np.sum, py_sum]:
25+
for func in [array_sum.array_sum, np.sum, py_sum]:
2626
total = 0.0
2727
start_time = timeit.default_timer()
2828
for iter_nr in range(options.iter):
2929
total += func(a)
3030
total_time = timeit.default_timer() - start_time
31-
print('{0:s}: {1:.6f} s ({2})'.format(func.__name__, total_time,
32-
total))
31+
print(f'{func.__name__:s}: {total_time:.6f} s ({total})')

0 commit comments

Comments
 (0)