Skip to content

Instantly share code, notes, and snippets.

@benoitrosa
Created August 29, 2017 07:33
Show Gist options
  • Save benoitrosa/5087120222c38a6646dfc8e04cad5d1d to your computer and use it in GitHub Desktop.
Save benoitrosa/5087120222c38a6646dfc8e04cad5d1d to your computer and use it in GitHub Desktop.
Numpy linalg.norm(A) vs np.sqrt(np.inner(A,A)
import numpy as np
import timeit
def norm(A):
if A.ndim == 1:
return np.sqrt(np.inner(A,A))
return np.linalg.norm(A)
def time_norms(A, n_eval):
start_time = timeit.default_timer()
for i in range(n_eval):
norm(A)
end_time = timeit.default_timer()
time_norm_ms = (end_time-start_time)*1.0/n_eval*10**3
start_time = timeit.default_timer()
for i in range(n_eval):
np.linalg.norm(A)
end_time = timeit.default_timer()
time_linalg_ms = (end_time-start_time)*1.0/n_eval*10**3
print "time(Norm)/time(np.linalg.norm) = ", time_norm_ms/time_linalg_ms
if __name__ == '__main__':
n_eval = 100
m = 35
for n in range(10,50,5):
print "n = ", n
A = np.random.rand(n)
print "1D array"
time_norms(A,n_eval)
A = np.random.rand(n,m)
print "2D array"
time_norms(A,n_eval)
A = np.random.rand(n,m,n)
print "3D array"
time_norms(A,n_eval)
print ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment