Created
July 11, 2021 10:20
-
-
Save EkremDincel/664a2916b7c9de78dd387314f46556c7 to your computer and use it in GitHub Desktop.
Basic Python profiler
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
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