Advertisement
zcutlip

python profiler

Jan 28th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. import timeit
  2.  
  3.  
  4. TIMER = None
  5.  
  6.  
  7. class TimeIt(object):
  8.     def __init__(self, max_depth):
  9.         self.max_depth = max_depth
  10.         self.timers = []
  11.  
  12.     def start_measure(self, name=None):
  13.         depth = len(self.timers)
  14.         if depth >= self.max_depth:
  15.             return
  16.         timer = timeit.default_timer()
  17.         if not name:
  18.             name = "timer %d" % depth + 1
  19.  
  20.         spaces = depth * "    "
  21.         print(spaces + "[%s] start" % name)
  22.         timer = timeit.default_timer()
  23.         self.timers.append((timer, name))
  24.  
  25.     def stop_measure(self):
  26.         # Not checking if we have any timers,
  27.         # because that's a pretty serious bug we should blow up on
  28.         # if len(self.timers) < 1:
  29.         #     return
  30.         start, name = self.timers.pop()
  31.         depth = len(self.timers)
  32.         spaces = depth * "    "
  33.         msg = ""
  34.         end = timeit.default_timer()
  35.         msg += spaces
  36.         msg += ("")
  37.         msg += ("[%s] end\t" % name)
  38.         msg += ("Elapsed time: %.3f seconds" % (end - start))
  39.         print(msg)
  40.         print("")
  41.  
  42.  
  43. def enable_timing(do_time, max_depth=10000):
  44.     global TIMER
  45.     if do_time and not TIMER:
  46.         TIMER = TimeIt(max_depth)
  47.  
  48.  
  49. def start_measure(name=None):
  50.     if TIMER:
  51.         TIMER.start_measure(name=name)
  52.  
  53.  
  54. def stop_measure():
  55.     if TIMER:
  56.         TIMER.stop_measure()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement