From 8ae639cb94bb2a92e3207e0bd4d4b1c49b59d6b4 Mon Sep 17 00:00:00 2001 From: Username Date: Fri, 26 Dec 2025 18:12:31 +0100 Subject: [PATCH] httpd: cache gc.get_objects and get_db_health calls --- httpd.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/httpd.py b/httpd.py index f5f74ad..8eaf369 100644 --- a/httpd.py +++ b/httpd.py @@ -53,6 +53,13 @@ _memory_sample_max = 60 # Keep last 60 samples (5 min at 5s intervals) _peak_rss = 0 _start_rss = 0 +# Cache for expensive operations +_gc_objects_cache = {'value': 0, 'time': 0} +_gc_objects_ttl = 30 # seconds + +_db_health_cache = {'value': {}, 'time': 0} +_db_health_ttl = 10 # seconds + def get_system_stats(): """Collect system resource statistics.""" @@ -139,7 +146,13 @@ def get_system_stats(): stats['gc_count_gen0'] = gc_counts[0] stats['gc_count_gen1'] = gc_counts[1] stats['gc_count_gen2'] = gc_counts[2] - stats['gc_objects'] = len(gc.get_objects()) + # Cache gc.get_objects() - expensive call (~23ms) + global _gc_objects_cache + now = time.time() + if now - _gc_objects_cache['time'] > _gc_objects_ttl: + _gc_objects_cache['value'] = len(gc.get_objects()) + _gc_objects_cache['time'] = now + stats['gc_objects'] = _gc_objects_cache['value'] except Exception: stats['gc_count_gen0'] = stats['gc_count_gen1'] = stats['gc_count_gen2'] = 0 stats['gc_objects'] = 0 @@ -148,7 +161,12 @@ def get_system_stats(): def get_db_health(db): - """Get database health and statistics.""" + """Get database health and statistics (cached).""" + global _db_health_cache + now = time.time() + if now - _db_health_cache['time'] < _db_health_ttl: + return _db_health_cache['value'] + stats = {} try: # Database file size @@ -211,6 +229,9 @@ def get_db_health(db): except Exception: pass + # Update cache + _db_health_cache['value'] = stats + _db_health_cache['time'] = time.time() return stats # Detect if gevent has monkey-patched the environment