silver2row

Trying the timeit library in Python3

Jul 27th, 2021
927
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # "Programming for Computations, (Langtangen, Linge 2020)."
  2.  
  3. import timeit
  4. import numpy as np
  5.  
  6. def add(a, b):
  7.     return a + b
  8.  
  9. x = np.zeros(1000)
  10. y = np.zeros(1000)
  11.  
  12. # use the function add
  13. t = timeit.Timer('for i in range(len(x)): x[i] = add(i, i + 1)', \
  14.                  setup='from __main__ import add, x')
  15. x_time = t.timeit(int(10000)) # time 10000 runs of the whole loop
  16. print('Time, function call: {:g} seconds'.format(x_time))
  17.  
  18. # do not use function add
  19. t = timeit.Timer('for i in range(len(y)): y[i] = i (i + 1)', \
  20.                  setup='from __main__ import y')
  21. y_time = t.timeit(int(10000)) # Time the 10000 runs of the entire loop
  22. print('Time: {:g} seconds'.format(y_time))
RAW Paste Data