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
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) |
Very convinient!
No comments:
Post a Comment