forked from rougier/from-python-to-numpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectorization.py
More file actions
44 lines (29 loc) · 1.01 KB
/
vectorization.py
File metadata and controls
44 lines (29 loc) · 1.01 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
# -----------------------------------------------------------------------------
# From Numpy to Python
# Copyright (2017) Nicolas P. Rougier - BSD license
# More information at https://github.com/rougier/numpy-book
# -----------------------------------------------------------------------------
import numpy as np
def compute_1(x, y):
""" Pure python version """
result = 0
for i in range(len(x)):
for j in range(len(y)):
result += x[i] * y[j]
return result
def compute_2(X, Y):
""" Numpy version, faster """
return (X.reshape(len(X), 1) * Y.reshape(1, len(Y))).sum()
def compute_3(X, Y):
""" Numpy version, fastest """
return X.sum()*Y.sum()
def compute_4(X, Y):
""" Pure python version, fastesr """
return sum(X)*sum(Y)
if __name__ == '__main__':
from tools import timeit
X = np.arange(1000)
timeit("compute_1(X,X)", globals())
timeit("compute_2(X,X)", globals())
timeit("compute_3(X,X)", globals())
timeit("compute_4(X,X)", globals())