Skip to content

Instantly share code, notes, and snippets.

@lykkin
Last active August 29, 2015 14:10
Show Gist options
  • Save lykkin/cf115bb24a5f93e8f7c9 to your computer and use it in GitHub Desktop.
Save lykkin/cf115bb24a5f93e8f7c9 to your computer and use it in GitHub Desktop.
dumb profiler stuff
from functools import wraps
from datetime import datetime
def memo(f):
cache = {}
@wraps(f)
def inner(*args, **kwargs):
key = str(args) + str(kwargs)
try:
return cache[key]
except KeyError:
cache[key] = f(*args, **kwargs)
return cache[key]
return inner
class Profiler():
tracking = {}
def time(self, f):
@wraps(f)
def inner(*args, **kwargs):
start = datetime.now()
res = f(*args, **kwargs)
try:
self.tracking[f.__name__]['runtime'] += datetime.now() - start
self.tracking[f.__name__]['times_run'] += 1
except KeyError:
self.tracking[f.__name__] = {
'runtime': datetime.now() - start,
'times_run': 1
}
return res
return inner
p = Profiler()
@p.time
@memo
def test1(n):
if n < 1:
return 1
return test1(n-1) + test1(n-2)
@p.time
def test2():
print '2'
test1(123)
for item in p.tracking.iteritems():
print item[0] + " ran for " + str(item[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment