Created
April 26, 2019 12:12
-
-
Save Jakobovski/191b9e95ac964b61e8abc7436111d1f9 to your computer and use it in GitHub Desktop.
A simple timer for python code blocks
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): | |
""" | |
A simple timer used to time blocks of code. Usage as follows: | |
with timer("optional_name"): | |
some code ... | |
some more code | |
""" | |
def __init__(self, name=None): | |
self.name = name | |
def __enter__(self): | |
self.start = time.time() | |
return self | |
def __exit__(self, *args): | |
self.end = time.time() | |
self.interval = self.end - self.start | |
if self.name: | |
print("{} - Elapsed time: {:.4f}s".format(self.name, self.interval)) | |
else: | |
print("Elapsed time: {:.4f}s".format(self.interval)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment