Actions
Code performance analysis¶
Execution time¶
Unscientific way → time module: One sample¶
Do not forget to configure your logger to the DEBUG level
from functools import wraps
from time import time
def timing(f):
@wraps(f)
def wrap(*args, **kw):
ts = time()
result = f(*args, **kw)
te = time()
_logger.debug('func:%r took: %2.4fs args:[%r, %r] ', f.__name__, te-ts, args, kw)
return result
return wrap
@timing
def my_func(a,b,c):
d = []
return a + b + c
Scientific way → timeit module¶
It runs a function multiple times to statisitically determine the execution time
Memory¶
To analyze the dynamic usage of memory within a function use the memory_profiler
python package. It will give you a line-by-line report of memory usage.
from memory_profiler import profile
@profile
def my_func(a,b,c):
d = [b + (c * i) for i in range(len(a))]
return d
Updated by Rafael Bailon-Ruiz about 4 years ago · 1 revisions