THE POST BELOW IS MORE THAN 5 YEARS OLD. RELATED SUPPORT INFORMATION MIGHT BE OUTDATED OR DEPRECATED
On 23/11/2012 at 06:17, xxxxxxxx wrote:
Just had this idea, but it comes with a little more code than I had expected. However, maybe you can find use for it.
# Copyright (C) 2012, Niklas Rosenstein
# Licensed under the GNU General Public License
import time
class Measure(object) :
""" This class implements measuring the time of code execution. It
also comes with an implementation of the `with` interface.
>>> width Measure() as t:
... time_heavy_stuff()
...
>>> print t.delta()
"""
def __init__(self) :
super(Measure, self).__init__()
self._start = -1
self._delta = -1
def __enter__(self) :
self.start()
return self
def __exit__(self, exc_type, exc_value, exc_tb) :
self.stop()
def start(self) :
self._delta = -1
self._start = time.time()
def stop(self) :
if self._start < 0:
raise RuntimeError('measuring must have been started before.')
self._delta = time.time() - self._start
self._start = -1
return self._delta
def current(self) :
if self._start < 0:
raise RuntimeError('measuring must have been started before.')
return time.time() - self._start
def delta(self) :
if self._delta < 0:
raise RuntimeError('measurement has not been stopped since the '
'last start.')
return self._delta
def reset(self) :
self._start = -1
self._delta = -1
def main() :
with Measure() as t:
time.sleep(0.5)
print t.delta()
main()