Thursday 28 July 2022

Record time taken for any python function

Here's a useful function for debugging a tools performance.

It's handy to know how long each section of your code is taking without having to sprinkle lots of time.time() functions around. Therefore, wouldn't it be nice to add a decorator to any function that you would like to print the execution time of?

import time
import functools

def record_time(f):
    """Print execution time of wrapped function."""
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        start = time.time()
        try:
            return f(*args, **kwargs)

        finally:
            print(f.__name__, "time taken:", time.time()-start)

    return wrapper

Now you can just add @record_time to line directly above any function definition, and when the function is called, the time will be printed like so;

@record_time
def jelly():
	for i in range(0,10000):
		print i

jelly()
# ('jelly', 'time taken:', 2.1070001125335693)

Happy debugging!