Skip to content

Instantly share code, notes, and snippets.

@omitakahiro
Last active February 17, 2020 01:23
Show Gist options
  • Save omitakahiro/1ddd34d5d8a4b059aec7b644bec92fca to your computer and use it in GitHub Desktop.
Save omitakahiro/1ddd34d5d8a4b059aec7b644bec92fca to your computer and use it in GitHub Desktop.
[Python] decorator to measure execution time of a function
import time

def stopwatch(info):
    def _decorator(func):
        def wrapper(*args, **kwargs):
            t1 = time.time()
            output = func(*args, **kwargs)
            t2 = time.time()
            print('%s: %.3fms' % (info,(t2-t1)*1000) )
            return output
        return wrapper
    return _decorator

usage

@stopwatch('sample code')
def test():
    x = 0
    for i in range(100000):
        x += i

test()
# output
sample code: 7.291ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment