Back to index

moin  1.9.0~rc2
clock.py
Go to the documentation of this file.
00001 # -*- coding: iso-8859-1 -*-
00002 """
00003     MoinMoin - Clock
00004 
00005     @copyright: 2001-2003 Juergen Hermann <jh@web.de>,
00006                 2003-2006 MoinMoin:ThomasWaldmann
00007     @license: GNU GPL, see COPYING for details.
00008 """
00009 
00010 import time
00011 
00012 class Clock:
00013     """ Helper class for code profiling
00014         we do not use time.clock() as this does not work across threads
00015         This is not thread-safe when it comes to multiple starts for one timer.
00016         It is possible to recursively call the start and stop methods, you
00017         should just ensure that you call them often enough :)
00018     """
00019 
00020     def __init__(self):
00021         self.timings = {}
00022         self.states = {}
00023 
00024     def _get_name(timer, generation):
00025         if generation == 0:
00026             return timer
00027         else:
00028             return "%s|%i" % (timer, generation)
00029     _get_name = staticmethod(_get_name)
00030 
00031     def start(self, timer):
00032         state = self.states.setdefault(timer, -1)
00033         new_level = state + 1
00034         name = Clock._get_name(timer, new_level)
00035         self.timings[name] = time.time() - self.timings.get(name, 0)
00036         self.states[timer] = new_level
00037 
00038     def stop(self, timer):
00039         state = self.states.setdefault(timer, -1)
00040         if state >= 0: # timer is active
00041             name = Clock._get_name(timer, state)
00042             self.timings[name] = time.time() - self.timings[name]
00043             self.states[timer] = state - 1
00044 
00045     def value(self, timer):
00046         base_timer = timer.split("|")[0]
00047         state = self.states.get(base_timer, None)
00048         if state == -1:
00049             result = "%.3fs" % self.timings[timer]
00050         elif state is None:
00051             result = "- (%s)" % state
00052         else:
00053             #print "Got state %r" % state
00054             result = "%.3fs (still running)" % (time.time() - self.timings[timer])
00055         return result
00056 
00057     def dump(self):
00058         outlist = []
00059         for timer in self.timings:
00060             value = self.value(timer)
00061             outlist.append("%s = %s" % (timer, value))
00062         outlist.sort()
00063         return outlist