From 5c177065dd83f93f3aef3a0b16255aa89f3f7fd7 Mon Sep 17 00:00:00 2001 From: Wirawan Purwanto Date: Wed, 27 Aug 2014 22:24:59 -0400 Subject: [PATCH] * Added block_timer class for use in python 2.5+ "with ..." construct. --- timer.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/timer.py b/timer.py index 0edc510..dc090a1 100644 --- a/timer.py +++ b/timer.py @@ -28,3 +28,49 @@ class timer: def length(self): return self.tm2 - self.tm1 + +class block_timer(object): + """Timer for a code block in python. + For use with python 2.5+ 'with' statement. + See: http://preshing.com/20110924/timing-your-code-using-pythons-with-statement + + To use this: + + with block_timer() as t: + + """ + @staticmethod + def writeout_file(out): + return lambda tm: out.write("Total execution time = %s secs\n" % (tm,)) + @staticmethod + def writeout_dict(rec, key): + def wrt_dict(tm): + rec[key] = tm + return wrt_dict + #return lambda tm: rec.__setitem__(key, tm) + + @staticmethod + def bt_file(fobj): + if isinstance(fobj, basestring): + from wpylib.iofmt.text_output import text_output + out = text_output(fobj) + else: + out = fobj + return block_timer(report=block_timer.writeout_file(out)) + + @staticmethod + def bt_dict(rec, key): + return block_timer(report=block_timer.writeout_dict(rec, key)) + + def __init__(self, report=None): + if report == None: report = block_timer.writeout_file(sys.stdout) + self.report = report + + def __enter__(self): + self.start = time.clock() + return self + + def __exit__(self, *args): + self.end = time.clock() + self.interval = self.end - self.start + self.report(self.interval)