Skip to content

Instantly share code, notes, and snippets.

@dwalkes
Created July 26, 2024 23:46
Show Gist options
  • Save dwalkes/6e158036e068263d6fa171933ef23afd to your computer and use it in GitHub Desktop.
Save dwalkes/6e158036e068263d6fa171933ef23afd to your computer and use it in GitHub Desktop.
Simple python class to log performance durations.
import time
class PerfClass:
'''
Simple python class to take performance measurements
Usage:
import time
perf = PerfClass()
start = time.perf_counter()
do_something_you_want_to_profile()
perf_class.log("something you want to profile", start)
...
perf_class.dump()
'''
def __init__(self):
self.perf_dict = {}
def log(self, entry, start_time):
duration = time.process_time() - start_time
if entry not in self.perf_dict:
self.perf_dict[entry] = ( duration, duration, duration, 1)
else:
min, max, avg, count = self.perf_dict[entry]
if duration < min:
min = duration
if duration > max:
max = duration
count = count+1
avg = (avg*(count-1))/(count) + duration/count
self.perf_dict[entry] = (min, max, avg, count)
def dump(self):
if len(self.perf_dict):
print("Entry,Min (ms), Max (ms), Average (ms), Count")
for entry in self.perf_dict:
min, max, avg, count = self.perf_dict[entry]
print(f"{entry},{min*1000},{max*1000},{avg*1000},{count}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment