Friday, July 6, 2018

Simple Tic Toc Alternative in Python

In Matlab, tic, toc functions provide very simple way to display time elapsed. We can create a similar mechanism in Python. Note that the source code below is only tested for Python3.


import time
class Timer(object):
def __init__(self, name=''):
self.name = name
def __enter__(self):
self.start = time.time()
def __exit__(self, *args):
elapsed = time.time() - self.start
print ('%s elapsed: %.2fs' % (self.name, elapsed))
if __name__ == '__main__':
with Timer('demo'):
time.sleep(5)
with Timer():
time.sleep(5)
view raw timer.py hosted with ❤ by GitHub

Very convinient!

No comments:

Post a Comment