Skip to content

Instantly share code, notes, and snippets.

@pybites
Created October 15, 2021 06:18
Embed
What would you like to do?
import cProfile
from functools import wraps
from pstats import Stats, SortKey
from time import time
def timing(f):
"""A simple timer decorator"""
@wraps(f)
def wrapper(*args, **kwargs):
start = time()
result = f(*args, **kwargs)
end = time()
print(f'Elapsed time {f.__name__}: {end - start}')
return result
return wrapper
def profile(f):
"""A simple timer decorator"""
@wraps(f)
def wrapper(*args, **kwargs):
with cProfile.Profile() as pr:
result = f(*args, **kwargs)
ps = Stats(pr)
print("Most time spent in general:")
ps.sort_stats(SortKey.CUMULATIVE).print_stats(10)
print("Functions taking most time:")
ps.sort_stats(SortKey.TIME).print_stats(10)
return result
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment