Skip to content

Instantly share code, notes, and snippets.

@joelburton
Created May 21, 2020 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/032b8e8f2a69ede404559614ef972c9b to your computer and use it in GitHub Desktop.
Save joelburton/032b8e8f2a69ede404559614ef972c9b to your computer and use it in GitHub Desktop.
from time import time
from random import random
# A "decorator" -- a function that:
# - takes a function as its arg
# - returns a "wrapped version" of that function
#
# In this case: the wrapped version runs the real function,
# but keeps track of how long it took to run.
def timeit(fn):
def wrapper(*args, **kwargs):
start_time = time()
result = fn(*args, **kwargs)
time_in_msec = int((time() - start_time) * 1000)
print(fn.__name__, f'({time_in_msec} ms)', args, result)
return result
return wrapper
# An example of a function we'd like to profile: to make it slow, give
# it a big `n` and a tiny `chance`
def slowish_thing(n, chance):
for i in range(n):
if random() < chance:
return True
return False
# A "wrapped" version of our function: we'll just reassign it to the same
# name --- now when you call this function, it will run timeit wrapped
# function, which ultimately calls the real slowish_thing
slowish_thing = timeit(slowish_thing)
print(slowish_thing(1000000, 0.00000001))
# same idea, but nicer syntax using a decorator
@timeit
def slowish_thing2(n, chance):
for i in range(n):
if random() < chance:
return True
return False
print(slowish_thing2(1000000, 0.00000001))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment