Skip to content

Instantly share code, notes, and snippets.

@root-11
Created July 23, 2019 08:17
Show Gist options
  • Save root-11/ed3753631aea6610b0edd501c66ec976 to your computer and use it in GitHub Desktop.
Save root-11/ed3753631aea6610b0edd501c66ec976 to your computer and use it in GitHub Desktop.
profiling decorator
import functools
import time
class Stack(object):
hits = {}
times = {}
@classmethod
def register(cls, func_name, call_time):
if func_name not in Stack.hits:
Stack.hits[func_name] = 0
Stack.times[func_name] = 0
Stack.hits[func_name] += 1
Stack.times[func_name] += call_time
@classmethod
def report(cls):
print('Calls made:')
for k in sorted(Stack.hits):
print(k, Stack.hits[k], Stack.times[k])
@staticmethod
def usage():
def decorator(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
start = time.time()
result = fn(*args, **kwargs)
end = time.time()
Stack.register(fn.__name__, call_time=end-start)
return result
return inner
return decorator
@Stack.usage()
def this():
time.sleep(0.01)
print('this')
@Stack.usage()
def that():
print('that')
time.sleep(0.1)
@Stack.usage()
def them():
time.sleep(0.001)
print('them')
def main():
for i in range(3):
this()
that()
for i in range(3):
them()
this()
main()
Stack.report()
# outputs:
# this
# that
# them
# ...
# them
# this
#
# Calls made:
# that 3 0.32779526710510254
# them 9 0.1409895420074463
# this 6 0.09374713897705078
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment