Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created October 2, 2016 17:18
Show Gist options
  • Save goldsborough/813f48c8a47f43a920b4e7b32afa14a7 to your computer and use it in GitHub Desktop.
Save goldsborough/813f48c8a47f43a920b4e7b32afa14a7 to your computer and use it in GitHub Desktop.
A benchmarking decorator that can handle recursive functions
def benchmark(function):
"""
Registers a function for benchmarking.
Args:
function (func): The function to benchmark.
Returns:
A new function with benchmarking functionality.
"""
# The start timestamp
start = None
@functools.wraps(function)
def proxy(*args, **kwargs):
"""
A proxy for the original function that performs benchmarking.
"""
# Need to reference the non-local start because we want to assign to it
nonlocal start
# Keep track of the very first call so that we only
# benchmark the outer call for recursive functions
is_first_call = start is None
if is_first_call:
start = time.time()
# Call the actual function we want to benchmark
result = function(*args, **kwargs)
# Benchmark only at the end of the first (outer most) call
if is_first_call:
# Compute the elapsed time
end = time.time()
delta = end - start
print('{0} took {1} seconds'.format(function.__name__, delta))
# Reset for further calls to this function
start = None
return result
return proxy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment