Created
January 23, 2017 11:28
-
-
Save titouanc/a02d5708d04977f4dcbf94dd9f3a83a0 to your computer and use it in GitHub Desktop.
Timer with subtimers in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import stdout | |
from time import time | |
from collections import OrderedDict | |
class Timer: | |
def __init__(self, autoshow=False): | |
self.subs = OrderedDict() | |
self.autoshow = autoshow | |
def __enter__(self): | |
self._start_time = time() | |
return self | |
def __exit__(self, *args, **kwargs): | |
self.time = time() - self._start_time | |
if self.autoshow: | |
self.show() | |
def sub(self, name): | |
res = Timer() | |
self.subs[name] = res | |
return res | |
def show(self, name='Total', indent=0, output=stdout): | |
prefix = " "*indent | |
print >>output, prefix, '*', name, ":", self.time | |
for name, val in self.subs.iteritems(): | |
val.show(name, indent+1) | |
if __name__ == "__main__": | |
from time import sleep | |
with Timer(True) as t: | |
sleep(1) | |
with t.sub('Lol') as t1: | |
sleep(1) | |
with t1.sub('haha'): | |
pass | |
with t.sub('Q'): | |
sleep(0.5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment