From 5a7013f471d185f95359f471a4a9dfa75e118f4d Mon Sep 17 00:00:00 2001 From: bucolucas Date: Sun, 18 Aug 2024 18:43:05 -0500 Subject: [PATCH] Add metrics.py for measuring function performance --- tools/metrics.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tools/metrics.py diff --git a/tools/metrics.py b/tools/metrics.py new file mode 100644 index 0000000..f4a695d --- /dev/null +++ b/tools/metrics.py @@ -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() \ No newline at end of file