Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # "Programming for Computations, (Langtangen, Linge 2020)."
- import timeit
- import numpy as np
- def add(a, b):
- return a + b
- x = np.zeros(1000)
- y = np.zeros(1000)
- # use the function add
- t = timeit.Timer('for i in range(len(x)): x[i] = add(i, i + 1)', \
- setup='from __main__ import add, x')
- x_time = t.timeit(int(10000)) # time 10000 runs of the whole loop
- print('Time, function call: {:g} seconds'.format(x_time))
- # do not use function add
- t = timeit.Timer('for i in range(len(y)): y[i] = i (i + 1)', \
- setup='from __main__ import y')
- y_time = t.timeit(int(10000)) # Time the 10000 runs of the entire loop
- print('Time: {:g} seconds'.format(y_time))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement