DEV Community

Carlos V.
Carlos V.

Posted on

4

Python decorator to measure function's execution time

I know we do some manual debugging from time to time. I got inspired from some Stack Overflow answers and blogposts to write this decorator

from functools import wraps
from time import process_time
def measure(func):
@wraps(func)
def _time_it(*args, **kwargs):
start = int(round(process_time() * 1000))
try:
return func(*args, **kwargs)
finally:
end_ = int(round(process_time() * 1000)) - start
print(
f"Total execution time {func.__name__}: {end_ if end_ > 0 else 0} ms"
)
return _time_it

Now, you just need to import it in your code and write something like:

@measure
def foo:
    some_large_computation()
Enter fullscreen mode Exit fullscreen mode

Output:

Total execution time foo: 15 ms
Enter fullscreen mode Exit fullscreen mode

If you want a smaller time unit, use 1000000 instead of 1000 factor to get microseconds (μ)

I hope this can be any help.

Top comments (1)

Collapse
 
zeedu_dev profile image
Eduardo Zepeda

Very useful! Thank you much for sharing!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay