Skip to content

Instantly share code, notes, and snippets.

@MBlore
Created April 17, 2023 22:20
Show Gist options
  • Save MBlore/a4bfd0fb2e6f4a0b929919eb77c4551e to your computer and use it in GitHub Desktop.
Save MBlore/a4bfd0fb2e6f4a0b929919eb77c4551e to your computer and use it in GitHub Desktop.
Performance Timer
import time
# PerfTimer is a class that allows us to use instances in a 'with' block thanks
# to the special '__enter__' and '__exit__' functions.
class PerfTimer:
def __init__(self, name):
self.name = name
def __enter__(self):
self.start_time = time.perf_counter()
def __exit__(self, type, value, traceback):
end_time = time.perf_counter()
elapsed = end_time - self.start_time
print(f"'{self.name}' taken: {elapsed} seconds.")
# Use the class in a 'with' block over the code you want to time.
with PerfTimer("Big For Loop") as p:
for i in range(100000000):
x = 0
x += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment