A Python Timing Decorator

One thing I’m always searching for is a timing decorator which gives me not not only the time spent, but also the function name.

This one prints to the standard output. An improvement could be to use logging instead, but I can’t always justify it.

def timeit(func):
    """A timing decorator"""
    from time import perf_counter
    from functools import wraps

    @wraps(func)
    def wrapper(*args, **kwargs):
        t_start = perf_counter()
        res = func(*args, **kwargs)
        elapsed = perf_counter() - t_start
        print(f"{func.__name__} took {elapsed}")
        return res
    return wrapper

It’s used as follows:

In [1]: @timeit
   ...: def process(input_):
   ...:     print(input_)
   ...:     time.sleep(1)
   ...:     return input_

In [2]: process([1, 2, 3])
[1, 2, 3]
process took 1.0013928239932284

The advantage of using perf_counter() over time.time() is that it has a higher resolution, and is targeted at short periods of time.