Created
September 17, 2018 12:20
-
-
Save pbelskiy/0de40ee50285fe174ba4f981543634fa to your computer and use it in GitHub Desktop.
Python function profiling time
This file contains hidden or 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
#!/usr/bin/env python3 | |
import time | |
class TimeProfiler: | |
functions = list() | |
start_time = instance = None | |
def __init__(self): | |
TimeProfiler.start_time = TimeProfiler.start_time or time.time() | |
def __del__(self): | |
total_time = time.time() - self.start_time | |
one_percent = total_time / 100 | |
print("\nExecution time (total {:.2f} seconds):".format(total_time)) | |
for (fname, ftime) in self.functions: | |
print(" - {}: {:.2f} seconds ({:4.1f}%) ".format( | |
fname, ftime, ftime / one_percent | |
)) | |
def start(self, name): | |
self.functions.append([name, time.time()]) | |
return len(self.functions) - 1 | |
def stop(self, index): | |
self.functions[index][1] = time.time() - self.functions[index][1] | |
@staticmethod | |
def this(f): | |
TimeProfiler.instance = TimeProfiler.instance or TimeProfiler() | |
def wrapper(*args, **kwargs): | |
try: | |
index = TimeProfiler.instance.start(f.__name__) | |
return f(*args, **kwargs) | |
finally: | |
TimeProfiler.instance.stop(index) | |
return wrapper | |
@TimeProfiler.this | |
def a(): | |
print("a") | |
time.sleep(0.1) | |
@TimeProfiler.this | |
def b(): | |
print("b") | |
time.sleep(0.2) | |
@TimeProfiler.this | |
def c(): | |
print("c") | |
# b() | |
time.sleep(0.3) | |
@TimeProfiler.this | |
def d(): | |
print("d") | |
a() | |
b() | |
c() | |
time.sleep(0.4) | |
d() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment