Add metrics.py for measuring function performance
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import cProfile
|
||||
import pstats
|
||||
import io
|
||||
from functools import wraps
|
||||
from collections import defaultdict
|
||||
|
||||
class Metrics:
|
||||
def __init__(self):
|
||||
self.call_count = defaultdict(int)
|
||||
self.total_time = defaultdict(float)
|
||||
|
||||
def measure(self, func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
self.call_count[func.__name__] += 1
|
||||
|
||||
pr = cProfile.Profile()
|
||||
pr.enable()
|
||||
|
||||
result = func(*args, **kwargs)
|
||||
|
||||
pr.disable()
|
||||
s = io.StringIO()
|
||||
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
|
||||
ps.print_stats()
|
||||
|
||||
# Extract the total time spent in the function
|
||||
time_spent = float(s.getvalue().split('\n')[0].split()[-2])
|
||||
self.total_time[func.__name__] += time_spent
|
||||
|
||||
return result
|
||||
return wrapper
|
||||
|
||||
def get_metrics(self):
|
||||
metrics = {}
|
||||
for func_name in self.call_count:
|
||||
metrics[func_name] = {
|
||||
'call_count': self.call_count[func_name],
|
||||
'total_time': self.total_time[func_name],
|
||||
'average_time': self.total_time[func_name] / self.call_count[func_name] if self.call_count[func_name] > 0 else 0
|
||||
}
|
||||
return metrics
|
||||
|
||||
# Create a global instance of Metrics
|
||||
metrics = Metrics()
|
||||
Reference in New Issue
Block a user