Skip to content

Instantly share code, notes, and snippets.

@EkremDincel
Created July 11, 2021 10:20
Show Gist options
  • Save EkremDincel/664a2916b7c9de78dd387314f46556c7 to your computer and use it in GitHub Desktop.
Save EkremDincel/664a2916b7c9de78dd387314f46556c7 to your computer and use it in GitHub Desktop.
Basic Python profiler
from contextlib import contextmanager
from timeit import default_timer as timer
try:
import matplotlib
except ModuleNotFoundError:
PLOT = False
else:
PLOT = True
class Profiler:
def __init__(self, name):
self.name = name
self.profiles = {}
@contextmanager
def scope(self, name):
start = timer()
try:
yield None
finally:
interval = timer() - start
self.profiles.setdefault(name, 0.0)
self.profiles[name] += interval
def plot(self):
if not PLOT:
raise ModuleNotFoundError("Module matplotlib is required for plotting but is not found.")
def log(self):
items = self.profiles.items()
items = sorted(items, key = lambda i: i[1], reverse = True)
for name, time in items:
print(f"{name}:\t{time}")
profiler = Profiler("my_profiler")
for i in range(10000):
with profiler.scope("sum"):
1 + 1
for i in range(100000):
with profiler.scope("sub"):
1 - 1
profiler.log()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment