DEV Community

Thomas Eckert
Thomas Eckert

Posted on • Updated on • Originally published at


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]

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

    return timed

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

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

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git