Skip to content

Instantly share code, notes, and snippets.

@Jakobovski
Created April 26, 2019 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jakobovski/191b9e95ac964b61e8abc7436111d1f9 to your computer and use it in GitHub Desktop.
Save Jakobovski/191b9e95ac964b61e8abc7436111d1f9 to your computer and use it in GitHub Desktop.
A simple timer for python code blocks
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