1. Use decorators to measure function execution time
There is a simple way, that is to define a decorator to measure the execution time of the function and output the result: (code common to 3.x)
import time from functools import wraps def fn_timer(function): @wraps(function) def function_timer(*args, **kwargs): t0 = time.time() result = function(*args, **kwargs) t1 = time.time() print("Total time running %s: %s seconds" % (function.__name__, str(t1-t0)) ) return result return function_timer
When you want to test the usage time of a function, you only need the @fn_timer decorator.
@fn_timer def myfunction(...): ...
Here is the test:
In [14]: @fn_timer ...: def norm(a): ...: return sum(a**2)**(1/2) ...: In [15]: @fn_timer ...: def norm2(a): ...: return la.norm(a) ...: In [16]: norm(a) Total time running norm: 0.0 seconds Out[16]: 4.7958315233127191 In [17]: norm2(a) Total time running norm2: 0.0 seconds Out[17]: 4.7958315233127191 In [18]: a = np.random.randint(-3,3,(10000,)) In [19]: norm(a) Total time running norm: 0.0010035037994384766 seconds Out[19]: 177.92695130305583 In [20]: norm2(a) Total time running norm2: 0.001010894775390625 seconds Out[20]: 177.92695130305583 In [21]: a = np.random.randint(-3,3,(50000,)) In [22]: norm(a) Total time running norm: 0.005008220672607422 seconds Out[22]: 397.39275282772837 In [23]: norm2(a) Total time running norm2: 0.0 seconds Out[23]: 397.39275282772837