Skip to main content
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

timestamp
float
Unix timestamp when snapshot was taken
rss
int
Resident Set Size (physical memory) in bytes
vms
int
Virtual Memory Size in bytes
cpu_percent
float
CPU utilization percentage

Methods

to_dict()
Convert snapshot to dictionary.
snapshot = CPUMemorySnapshot(...)
data = snapshot.to_dict()
return
Dict[str, Any]
Dictionary representation of the snapshot

CPUProfileResult

Results from profiling a CPU function or context.
from gpumemprof.cpu_profiler import CPUProfileResult

Attributes

name
str
Name of the profiled function or context
duration
float
Execution duration in seconds
snapshot_before
CPUMemorySnapshot
Memory snapshot before execution
snapshot_after
CPUMemorySnapshot
Memory snapshot after execution
peak_rss
int
Peak RSS during execution in bytes

Methods

memory_diff()
Calculate memory difference.
result = profiler.profile_function(my_func)
diff = result.memory_diff()
return
int
RSS difference in bytes
to_dict()
Convert result to dictionary.
data = result.to_dict()
return
Dict[str, Any]
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")
func
Callable
Function to profile
*args
Any
Function arguments
**kwargs
Any
Function keyword arguments
return
CPUProfileResult
Profiling result
profile_context()
Context manager for profiling code blocks.
with profiler.profile_context("data_processing"):
    data = [process(x) for x in items]
name
str
default:"'context'"
Name for the profiled context
start_monitoring()
Start continuous memory monitoring.
profiler.start_monitoring(interval=0.5)
# ... run code ...
profiler.stop_monitoring()
interval
float
default:"0.1"
Monitoring interval in seconds
stop_monitoring()
Stop continuous memory monitoring.
profiler.stop_monitoring()
clear_results()
Clear all profiling results.
profiler.clear_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']}")
return
Dict[str, Any]
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
float
default:"0.5"
Sampling interval in seconds
max_events
int
default:"10000"
Maximum events to keep in ring buffer
enable_alerts
bool
default:"True"
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.
tracker.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
return
List[TrackingEvent]
Filtered tracking events
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']}")
return
Dict[str, Any]
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']}")
interval
float
default:"1.0"
Time interval for aggregation
return
Dict[str, List[float]]
Timeline with timestamps, allocated, and reserved lists
clear_events()
Clear all events.
tracker.clear_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")
filename
str
Output filename
format
str
default:"'csv'"
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}")
directory
str
Output directory
format
str
Export format
return
str
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']}")

Build docs developers (and LLMs) love