Skip to content

Instantly share code, notes, and snippets.

@blaylockbk
Last active July 10, 2021 16:59
Show Gist options
  • Save blaylockbk/93246ac93f6817ec569755d93f669dde to your computer and use it in GitHub Desktop.
Save blaylockbk/93246ac93f6817ec569755d93f669dde to your computer and use it in GitHub Desktop.
A decorator to time a function execution time
def timer(func):
"""
A decorator to time a function execution time.
Based on https://twitter.com/pybites/status/1387691670658068481?s=20
Parameters
----------
func : function
The function you wish to time.
Usage
-----
>>> from time import sleep
>>> @timer
>>> def snooze(x):
>>> print('I am a sleeping giant...💤')
>>> sleep(x)
>>> return "AWAKE! 👹"
>>> snooze(3)
>>> #
>>> #out: I am a sleeping giant...💤
>>> #out: ⏱ Timer [snooze]: 0:00:03.004211
>>> #out: 'AWAKE! 👹'
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = datetime.now()
ret = func(*args, **kwargs)
duration = datetime.now() - start
print(f"⏱ Timer [{func.__name__}]: {duration}")
return ret
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment