snippets/Python-decorator-to-measure...

32 lines
933 B
Markdown

# decorator to measure the execution time per line
This decorator measures the amount of time it takes to execute a function and displays a detailed summary.
```Python
from cProfile import Profile
def explain_time(f):
def wrapper(*args, **kwargs):
profile = Profile()
profile.enable()
output = f(*args, **kwargs)
profile.disable()
profile.print_stats()
return output
return wrapper
@explain_time
def test():
d = {"a": -1}
return d.get("a")
>>> test()
3 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <ipython-input-209-8a9237b67823>:11(test)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {method 'get' of 'dict' objects}
```