Created
January 9, 2014 15:38
-
-
Save pierre-haessig/8336087 to your computer and use it in GitHub Desktop.
TicToc timing class 1st time an instance is called, it sets a timestamp (time.time())
2nd time, it computes and returns the difference (in seconds, float).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TicToc(object): | |
'''Timing class | |
1st time an instance is called, it sets a timestamp (time.time()) | |
2nd time, it computes and returns the difference (in seconds, float). | |
Examples | |
-------- | |
>>> t = TicToc() | |
>>> t() # returns time.time() | |
1389281072.45 | |
>>> time.sleep(0.1) | |
>>> t() | |
0.100247144699 | |
''' | |
def __init__(self, fmt=None): | |
from time import time | |
self.time = time | |
self.start = None | |
self.fmt = fmt | |
def __call__(self, *args): | |
if self.start is None: | |
return self.tic() | |
else: | |
return self.toc() | |
def tic(self): | |
t = self.time() | |
self.start = t | |
return t | |
def toc(self): | |
t2 = self.time() | |
delta = t2 - self.start | |
if self.fmt is not None: | |
print(self.fmt.format(delta)) | |
# reset the TicToc: | |
self.start = None | |
return delta | |
if __name__ == '__main__': | |
import time | |
t = TicToc() | |
print(t()) | |
time.sleep(0.1) | |
print(t()) | |
# with printing | |
t() | |
t.fmt = 'simulation time: {:.2f} s' | |
time.sleep(0.2) | |
print(t()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment