Guest User

Untitled

a guest
Jul 19th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. def alt_cosine(x,y):
  2. return 1 - np.inner(x,y)/np.sqrt(np.dot(x,x)*np.dot(y,y))
  3.  
  4. from libc.math cimport sqrt
  5. def alt_cosine_2(x,y):
  6. return 1 - np.inner(x,y)/sqrt(np.dot(x,x)*np.dot(y,y))
  7.  
  8. >>> cosine() # ... make some timings
  9. 5.27526156300155e-05 # mean calculation time for one loop
  10.  
  11. >>> alt_cosine()
  12. 9.913400815003115e-06
  13.  
  14. >>> alt_cosine_2()
  15. 7.0269494536660205e-06
  16.  
  17. import numpy as np
  18.  
  19. def f1(x, y):
  20. return 1 - np.inner(x,y)/np.sqrt(np.dot(x,x)*np.dot(y,y))
  21.  
  22. from numpy import inner, sqrt, dot
  23.  
  24. def f2(x, y):
  25. return 1 - inner(x,y)/sqrt(dot(x,x)*dot(y,y))
  26.  
  27. x = np.ones(100000)
  28.  
  29. %timeit f1(x,x)
  30. # 58.1 µs ± 19.1 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  31.  
  32. %timeit f2(x,x)
  33. # 36.3 µs ± 3.32 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  34.  
  35. def f3(x, y, inner=inner, sqrt=sqrt, dot=dot):
  36. return 1 - inner(x,y)/sqrt(dot(x,x)*dot(y,y))
  37.  
  38. %timeit f3(x,x)
  39. # 36.5 µs ± 3.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Add Comment
Please, Sign In to add comment