0775204345e60a94146164feb2966bdecb886642
[tabakrolletjie.git] / tabakrolletjie / utils.py
1 """ Tabakutilities. """
2
3 import functools
4 import time
5
6 from .constants import DEBUG
7
8
9 def debug_timer(label, debug=False):
10     """ A decorator for printing how long a function took if debug is true.
11     """
12     def debug_inner(f):
13         @functools.wraps(f)
14         def wrapper(*args, **kw):
15             start_time = time.time()
16             try:
17                 return f(*args, **kw)
18             finally:
19                 duration = time.time() - start_time
20                 if DEBUG or debug:
21                     print "%s [%g seconds]" % (label, duration)
22         return wrapper
23     return debug_inner
24
25
26 class DetailedTimer(object):
27     """ A detailed timer for overly complex functions.
28     """
29     def __init__(self, title, debug=False):
30         if DEBUG or debug:
31             self.title = title
32             self.times = []
33         else:
34             # fast funtions with the correct signature
35             self.start = int
36             self.show = str
37             self.lap = str
38             self.end = int
39
40     def start(self):
41         print "---- %s ----" % self.title
42         self.times.append(time.time())
43
44     def lap(self, label):
45         now = time.time()
46         print "  %s: %s" % (label, now - self.times[-1])
47         self.times.append(now)
48
49     def show(self, text):
50         print "  %s" % text
51
52     def end(self):
53         print "  %s: %s" % ("total", time.time() - self.times[0])
54         print "---- ----"