DEV Community

Ahmed El Taweel
Ahmed El Taweel

Posted on

23 3

Python decorator to show execution time of a function

When working on a high throughput, low latency system, it's important to measure the execution time of your code to identify bottleneck and fix them. To do so, let's use a decorator to measure the execution time for the function it decorates.


from datetime import timedelta
from functools import wraps
from timeit import default_timer as timer
from typing import Any, Callable, Optional


def metrics(func: Optional[Callable] = None, name: Optional[str] = None, hms: Optional[bool] = False) -> Any:
    """Decorator to show execution time.

    :param func: Decorated function
    :param name: Metrics name
    :param hms: Show as human-readable string
    """
    assert callable(func) or func is None

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            comment = f"Execution time of {name or fn.__name__}:"
            t = timer()
            result = fn(*args, **kwargs)
            te = timer() - t

            # Log metrics
            from common import log
            logger = log.withPrefix('[METRICS]')
            if hms:
                logger.info(f"{comment} {timedelta(seconds=te)}")
            else:
                logger.info(f"{comment} {te:>.6f} sec")

            return result
        return wrapper

    return decorator(func) if callable(func) else decorator
Enter fullscreen mode Exit fullscreen mode

By adding this decorator to each function, we can use the analytics from the APM to identify bottleneck and gain better visibility over the system.

Happy coding :D

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (3)

Collapse
 
abanoub7asaad profile image
Abanoub Asaad

I like it :)

Collapse
 
cereal84 profile image
Alessandro Pischedda

Nice

Collapse
 
chilango74 profile image
Sergey Kikevich

Thanks! Interesting ... Will use it

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