DEV Community

Thomas Eckert
Thomas Eckert

Posted on • Edited on • Originally published at thomaseckert.dev

3 3

Logging Python Execution Time with a Decorator

Here is a decorator for logging execution time for a Python function:

from time import time


def print_execution_time(function):
    def timed(*args, **kw):
        time_start = time()
        return_value = function(*args, **kw)
        time_end = time()

        execution_time = time_end - time_start

        arguments = ", ".join(
            [str(arg) for arg in args] + ["{}={}".format(k, kw[k]) for k in kw]
        )

        print(
            "{} ms {}({})".format(
                str(execution_time * 1000), function.__name__, arguments
            )
        )
        return return_value

    return timed


@print_execution_time
def repeat(number, n_repeats=30000):
    return [number for number in range(30000)]


repeat(9)
repeat(20, 40000)
repeat(1, n_repeats=4000)
Enter fullscreen mode Exit fullscreen mode

This will print the execution time in milliseconds and the name of the function run with its arguments:

1.001596450805664 ms repeat(9)
1.0008811950683594 ms repeat(20, 40000)
1.0001659393310547 ms repeat(1, n_repeats=4000)
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay