Skip to content

Instantly share code, notes, and snippets.

@kanghyojun
Last active December 24, 2015 06:49
Show Gist options
  • Select an option

  • Save kanghyojun/6760006 to your computer and use it in GitHub Desktop.

Select an option

Save kanghyojun/6760006 to your computer and use it in GitHub Desktop.
class Timer(object):
def __init__(self):
self.start = None
self.l = []
def mark(self, name=''):
from time import time
if name:
print name + ' marked.'
if not self.start:
self.start = time()
else:
t = time() - self.start
diff = 0
if self.l:
diff = t - self.l[len(self.l) - 1][1]
self.l.append((name , t, diff))
def clear(self):
self.l = []
def __repr__(self):
r = ""
for i, x in enumerate(self.l):
if x[0]:
r += "%d mark `%s`, %.2f seconds, %.2fs consumed\n" % (i, x[0], x[1], x[2])
else:
r += "%d mark, %.2f seconds, %.2fs consumed\n\n" % (i, x[1], x[2])
if self.l:
avg = sum([x[2] for x in self.l]) / float(len(self.l))
r += 'run %d in %.2fs, average: %.2fs\n' % (len(self.l),
self.l[len(self.l) - 1][1],
avg)
return r
@kanghyojun
Copy link
Copy Markdown
Author

t = Timer()
t.mark()
#do some process
t.mark(name='process1')
#do another process
t.mark(name='process2')
print t
"""
 0 mark `process1`, 2.24 seconds
 1 mark `process2`, 3.34 seconds
"""

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment