|
| 1 | +"""Memory utility functions for monitoring and optimization.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import gc |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import psutil |
| 9 | + |
| 10 | +from gitingest.utils.logging_config import get_logger |
| 11 | + |
| 12 | +logger = get_logger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +def get_memory_usage() -> dict[str, Any]: |
| 16 | + """Get current memory usage statistics. |
| 17 | +
|
| 18 | + Returns |
| 19 | + ------- |
| 20 | + dict[str, Any] |
| 21 | + Dictionary containing memory usage statistics in MB. |
| 22 | +
|
| 23 | + """ |
| 24 | + try: |
| 25 | + process = psutil.Process() |
| 26 | + memory_info = process.memory_info() |
| 27 | + |
| 28 | + return { |
| 29 | + "rss_mb": memory_info.rss / (1024 * 1024), # Resident Set Size |
| 30 | + "vms_mb": memory_info.vms / (1024 * 1024), # Virtual Memory Size |
| 31 | + "percent": process.memory_percent(), |
| 32 | + } |
| 33 | + except Exception as exc: |
| 34 | + logger.warning("Failed to get memory usage", extra={"error": str(exc)}) |
| 35 | + return {"rss_mb": 0, "vms_mb": 0, "percent": 0} |
| 36 | + |
| 37 | + |
| 38 | +def force_garbage_collection() -> None: |
| 39 | + """Force garbage collection to free up memory.""" |
| 40 | + try: |
| 41 | + collected = gc.collect() |
| 42 | + logger.debug("Forced garbage collection", extra={"objects_collected": collected}) |
| 43 | + except Exception as exc: |
| 44 | + logger.warning("Failed to force garbage collection", extra={"error": str(exc)}) |
| 45 | + |
| 46 | + |
| 47 | +def check_memory_pressure(threshold_mb: float = 3000) -> bool: |
| 48 | + """Check if memory usage is above threshold. |
| 49 | +
|
| 50 | + Parameters |
| 51 | + ---------- |
| 52 | + threshold_mb : float |
| 53 | + Memory threshold in MB (default: 3000 MB = 3 GB). |
| 54 | +
|
| 55 | + Returns |
| 56 | + ------- |
| 57 | + bool |
| 58 | + True if memory usage is above threshold. |
| 59 | +
|
| 60 | + """ |
| 61 | + memory_stats = get_memory_usage() |
| 62 | + return memory_stats["rss_mb"] > threshold_mb |
| 63 | + |
| 64 | + |
| 65 | +def log_memory_stats(context: str = "") -> None: |
| 66 | + """Log current memory statistics. |
| 67 | +
|
| 68 | + Parameters |
| 69 | + ---------- |
| 70 | + context : str |
| 71 | + Context information for the log message. |
| 72 | +
|
| 73 | + """ |
| 74 | + memory_stats = get_memory_usage() |
| 75 | + logger.info( |
| 76 | + "Memory usage %s", |
| 77 | + context, |
| 78 | + extra={ |
| 79 | + "memory_rss_mb": round(memory_stats["rss_mb"], 2), |
| 80 | + "memory_vms_mb": round(memory_stats["vms_mb"], 2), |
| 81 | + "memory_percent": round(memory_stats["percent"], 2), |
| 82 | + }, |
| 83 | + ) |
0 commit comments