The cpu_profiler module provides memory profiling for CPU-only environments, mirroring the GPU profiler API.
Classes
CPUMemorySnapshot
Point-in-time CPU memory snapshot.
from gpumemprof.cpu_profiler import CPUMemorySnapshot
Attributes
Unix timestamp when snapshot was taken
Resident Set Size (physical memory) in bytes
Virtual Memory Size in bytes
CPU utilization percentage
Methods
to_dict()
Convert snapshot to dictionary.
snapshot = CPUMemorySnapshot(...)
data = snapshot.to_dict()
Dictionary representation of the snapshot
CPUProfileResult
Results from profiling a CPU function or context.
from gpumemprof.cpu_profiler import CPUProfileResult
Attributes
Name of the profiled function or context
Execution duration in seconds
Memory snapshot before execution
Memory snapshot after execution
Peak RSS during execution in bytes
Methods
memory_diff()
Calculate memory difference.
result = profiler.profile_function(my_func)
diff = result.memory_diff()
to_dict()
Convert result to dictionary.
Dictionary with profiling metrics
CPUMemoryProfiler
Lightweight CPU memory profiler mirroring the GPU API.
from gpumemprof.cpu_profiler import CPUMemoryProfiler
profiler = CPUMemoryProfiler()
Methods
profile_function()
Profile a function execution.
def compute_heavy(data):
result = [x * 2 for x in data]
return result
result = profiler.profile_function(compute_heavy, large_data)
print(f"Duration: {result.duration:.3f}s")
print(f"Memory change: {result.memory_diff() / 1024**2:.2f} MB")
Function keyword arguments
profile_context()
Context manager for profiling code blocks.
with profiler.profile_context("data_processing"):
data = [process(x) for x in items]
Name for the profiled context
start_monitoring()
Start continuous memory monitoring.
profiler.start_monitoring(interval=0.5)
# ... run code ...
profiler.stop_monitoring()
Monitoring interval in seconds
stop_monitoring()
Stop continuous memory monitoring.
profiler.stop_monitoring()
clear_results()
Clear all profiling results.
get_summary()
Get profiling summary.
summary = profiler.get_summary()
print(f"Peak memory: {summary['peak_memory_usage']}")
print(f"Snapshots collected: {summary['snapshots_collected']}")
Summary with mode=‘cpu’, snapshots, peak memory, and baseline info
CPUMemoryTracker
CPU tracker offering a superset of the GPU tracker interface.
from gpumemprof.cpu_profiler import CPUMemoryTracker
tracker = CPUMemoryTracker(
sampling_interval=0.5,
max_events=10000,
enable_alerts=True
)
Constructor
Sampling interval in seconds
Maximum events to keep in ring buffer
Whether to enable memory alerts
Methods
start_tracking()
Start real-time CPU memory tracking.
tracker.start_tracking()
# ... run code ...
tracker.stop_tracking()
stop_tracking()
Stop tracking.
get_events()
Get tracking events with filtering.
# All events
events = tracker.get_events()
# Filter by type
allocations = tracker.get_events(event_type="allocation")
# Last N events
recent = tracker.get_events(last_n=50)
# Since timestamp
import time
events = tracker.get_events(since=time.time() - 3600)
event_type
Optional[str]
default:"None"
Filter by event type
last_n
Optional[int]
default:"None"
Get last N events
since
Optional[float]
default:"None"
Get events since timestamp
get_statistics()
Get tracking statistics.
stats = tracker.get_statistics()
print(f"Mode: {stats['mode']}")
print(f"Peak memory: {stats['peak_memory']}")
print(f"Current RSS: {stats['current_memory_allocated']}")
Statistics including mode, peak memory, and duration
get_memory_timeline()
Get memory usage timeline.
timeline = tracker.get_memory_timeline(interval=1.0)
print(f"Timestamps: {timeline['timestamps']}")
print(f"Allocated: {timeline['allocated']}")
Time interval for aggregation
Timeline with timestamps, allocated, and reserved lists
clear_events()
Clear all events.
export_events()
Export events to file.
# CSV export
tracker.export_events("cpu_memory.csv", format="csv")
# JSON export
tracker.export_events("cpu_memory.json", format="json")
Export format: ‘csv’ or ‘json’
export_events_with_timestamp()
Export events with automatic timestamped filename.
filename = tracker.export_events_with_timestamp(
directory="./logs",
format="csv"
)
print(f"Exported to: {filename}")
Full path to exported file
Example Usage
from gpumemprof.cpu_profiler import (
CPUMemoryProfiler,
CPUMemoryTracker
)
# Profile individual functions
profiler = CPUMemoryProfiler()
def process_data(data):
return [x * 2 for x in data]
result = profiler.profile_function(process_data, range(1000000))
print(f"Duration: {result.duration:.3f}s")
print(f"Memory change: {result.memory_diff() / 1024**2:.2f} MB")
# Context-based profiling
with profiler.profile_context("computation"):
large_list = [i ** 2 for i in range(1000000)]
# Continuous tracking
tracker = CPUMemoryTracker(sampling_interval=0.1)
tracker.start_tracking()
# Run your CPU-intensive code
for i in range(100):
data = [x * 2 for x in range(10000)]
tracker.stop_tracking()
# Analyze results
stats = tracker.get_statistics()
print(f"Peak RSS: {stats['peak_memory'] / 1024**2:.2f} MB")
print(f"Total events: {stats['total_events']}")
# Export timeline
tracker.export_events("cpu_profile.csv")
# Get summary
summary = profiler.get_summary()
print(f"Snapshots collected: {summary['snapshots_collected']}")