5.3. Profiling Sampling

  • Sampling profiler

  • profiling.sampling

  • Statistical sampling. Best for production profiling, CPU analysis, I/O bottlenecks, multithreaded applications and low-overhead performance investigation.

  • Tachyon is a high-frequency statistical sampling profiler that provides low-overhead profiling for Python applications. It is designed to help developers identify performance bottlenecks and optimize their code.

  • Tachyon has achieved a sampling frequency of 1,000,000 samples per second (1 MHz), which is significantly higher than traditional sampling profilers. This allows for more accurate profiling of short-lived functions and high-frequency events.

  • https://docs.python.org/3/whatsnew/3.15.html#tachyon-high-frequency-statistical-sampling-profiler

Sampling periodically captures the execution stacks of running threads. It estimates where execution time is spent without instrumenting every function call.

5.3.1. Profile Script

$ python -m profiling.sampling run myfile.py

On macOS, you may encounter a permission error when trying to profile processes. This is due to the operating system's security restrictions. To resolve this, you can run the profiling command with elevated permissions using sudo:

$ python -m profiling.sampling run main.py
Permission Error: Unable to access process memory on macOS

Tachyon needs elevated permissions to profile processes. Try one of these solutions:

1. Try running again with elevated permissions by running 'sudo -E !!'.

2. If targeting system Python processes:
   Note: Apple's System Integrity Protection (SIP) may block access to system
   Python binaries. Consider using a user-installed Python instead.
$ sudo python -m profiling.sampling run main.py
Password:
Wall time: 3.951s
CPU time:  3.951s
Captured 3956 samples in 3.96 seconds
Sample rate: 999.97 samples/sec
Error rate: 37.29
Profile Stats:
       nsamples   sample%   tottime (s)    cumul%   cumtime (s)  filename:lineno(function)
      2117/2481      85.3         2.117     100.0         2.481  main.py:6(<module>)
        364/364      14.7         0.364      14.7         0.364  main.py:6(<genexpr>)
         0/2481       0.0         0.000     100.0         2.481  <frozen runpy>:87(_run_code)
         0/2481       0.0         0.000     100.0         2.481  <frozen runpy>:201(_run_module_as_main)

Legend:
  nsamples: Direct/Cumulative samples (direct executing / on call stack)
  sample%: Percentage of total samples this function was directly executing
  tottime: Estimated total time spent directly in this function
  cumul%: Percentage of total samples when this function was on the call stack
  cumtime: Estimated cumulative time (including time in called functions)
  filename:lineno(function): Function location and name

Summary of Interesting Functions:

Functions with Highest Direct/Cumulative Ratio (Hot Spots):
  1.000 direct/cumulative ratio, 14.7% direct samples: main.py:(<genexpr>)
  0.853 direct/cumulative ratio, 85.3% direct samples: main.py:(<module>)

Functions with Highest Call Frequency (Indirect Calls):
  2481 indirect calls, 100.0% total stack presence: <frozen runpy>:(_run_code)
  2481 indirect calls, 100.0% total stack presence: <frozen runpy>:(_run_module_as_main)
  364 indirect calls, 100.0% total stack presence: main.py:(<module>)

Functions with Highest Call Magnification (Cumulative/Direct):
  1.2x call magnification, 364 indirect calls from 2117 direct: main.py:(<module>)

5.3.2. Profile Module

$ python -m profiling.sampling run -m mypackage.module

5.3.3. Parameters

  • -d or --duration - Duration of profiling in seconds

  • -i or --interval - Sampling interval in microseconds

  • -m or --mode - Profiling mode (wall, cpu, gil, exception)

  • wall - Real elapsed time - General application profiling

  • cpu - Actual CPU execution time - CPU-bound workloads

  • gil - Time holding the GIL - Multithreading analysis

  • exception - Execution associated with active exceptions - Exception-heavy workloads

Profile for 30 seconds, sampling every 50 microseconds:

$ python -m profiling.sampling run -i 50 -d 30 myfile.py
$ python -m profiling.sampling run --mode cpu myfile.py

To investigate GIL contention:

$ python -m profiling.sampling run --mode gil myfile.py

5.3.4. Flame Graphs

  • Identify functions consuming the most execution time.

  • Identify expensive call hierarchies.

  • Identify unexpectedly deep call stacks.

  • Identify hot paths in complex applications.

  • The width of a stack frame represents its contribution to the collected samples.

Flame graphs help identify:

  • Functions consuming the most execution time.

  • Expensive call hierarchies.

  • Unexpectedly deep call stacks.

  • Hot paths in complex applications.

The width of a stack frame represents its contribution to the collected samples.

One of the most useful features is flame graph generation:

$ python -m profiling.sampling run --flamegraph myfile.py
Wall time: 3.944s
CPU time:  3.944s
Captured 3949 samples in 3.95 seconds
Sample rate: 999.97 samples/sec
Error rate: 37.98
Flamegraph data: 1 root function, 2449 total samples, 17 unique strings
Flamegraph saved to: flamegraph_59674.html

5.3.5. Attach to a Running Process

  • Useful for profiling long-running services, workers and production applications.

This is particularly useful for long-running services, workers and production applications.

Find the PID:

$ ps aux | grep myfile.py
$ python -m profiling.sampling attach <pid>

Profile for 30 seconds:

$ python -m profiling.sampling attach <pid> -d 30

5.3.6. Multithreaded applications

  • By default, you can select whether to profile all threads or just the main thread.

  • Use -a to profile all threads

  • Identify uneven workload distribution.

  • Identify thread contention.

  • Identify blocking operations.

  • Identify GIL bottlenecks.

This is useful for identifying: - Uneven workload distribution. - Thread contention. - Blocking operations. - GIL bottlenecks.

Use -a to profile all threads:

$ python -m profiling.sampling run -a myfile.py

5.3.7. Native extensions

  • By default, native extensions are not profiled.

  • Use -n or --native to profile native extensions.

Sampling can also reveal execution in native C extensions:

$ python -m profiling.sampling run --native myfile.py

This is particularly useful when working with NumPy, SciPy, PyTorch or custom C/C++ extensions.

It helps distinguish Python-level overhead from native execution.

5.3.8. Heatmaps

  • Identify functions consuming the most execution time.

  • Identify expensive call hierarchies.

  • Identify unexpectedly deep call stacks.

Generate line-level heatmaps:

$ python -m profiling.sampling run --heatmap myfile.py

The profiler generates interactive HTML visualizations showing where execution samples accumulate in individual source files.

5.3.9. Async Applications

For asyncio applications, use:

$ python -m profiling.sampling run --async-aware myfile.py

This reconstructs coroutine execution stacks and helps distinguish running tasks from tasks waiting on asynchronous operations.

5.3.10. Live profiling

You can also monitor an application interactively:

$ python -m profiling.sampling run --live myfile.py

This provides a real-time, top-like interface for inspecting execution hotspots.