Scalene-Agents.md
python3 -m scalene --cli --json --outfile profile.json script.py
Scalene's key differentiator is separating Python time from C/native time:
n_cpu_percent_python: Time spent executing Python bytecode - this is your optimization targetn_cpu_percent_c: Time spent in C extensions/native code - generally NOT optimizable at the Python levelCritical insight: Focus optimization efforts on code with high Python time. Code spending most of its time in C is already running native code and can only be improved by:
For example, Python's slice reversal perm[:k+1] = perm[k::-1] shows high C time because it's implemented in C. Replacing it with a Python loop makes performance worse because it moves work from fast C code to slow Python code.
Scalene tracks detailed memory behavior:
n_malloc_mb: Memory allocated on this linen_peak_mb: Peak memory usage attributed to this linen_avg_mb: Average memory footprintn_growth_mb: Net memory growth (allocations minus frees) - useful for detecting memory leaksn_usage_fraction: Fraction of total memory used by this lineWhen to focus on memory:
n_growth_mb with n_python_fraction near 1.0 indicates Python objects accumulating (potential leak)n_peak_mb suggests opportunities to reduce memory footprint by processing data in chunksn_copy_mb_s: Rate of memory copying in MB/s attributed to this lineWhy this matters: High copy volume indicates inefficient data handling:
join() or io.StringIO)Example: A line showing 100+ MB/s copy volume in a data processing loop suggests refactoring to avoid intermediate copies.
n_gpu_percent: Percentage of GPU timen_gpu_avg_memory_mb: Average GPU memory usagen_gpu_peak_memory_mb: Peak GPU memory usagen_sys_percent: Time spent in system calls (I/O, etc.)High system time may indicate:
Check Python vs C time split
Check memory growth
Check copy volume
Check system time