> ## Documentation Index
> Fetch the complete documentation index at: https://codspeed.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# CPU Simulation Instrument

> Learn how to use CodSpeed's CPU simulation instrument for consistent, hardware-agnostic performance measurement in your benchmarks

## What is CPU Simulation?

CodSpeed instruments your benchmarks to measure the performance of your code,
simulating the CPU behavior. A benchmark will be run **only once** and the CPU
behavior will be simulated. This ensures that the measurement is as accurate as
possible, taking into account not only the instructions executed but also the
cache and memory access patterns. The simulation gives us an equivalent of the
CPU cycles that includes cache and memory access.

### Estimating Cycles

The CPU simulation takes into account the following factors:

1. **Executed instruction cycles** (`Icycles`): the baseline cost of your code,
   where each instruction is weighted by its cost on real hardware
2. **L1 cache misses**: data that must be fetched from L2/L3 cache, this can
   take 10-40 cycles
3. **LL (Last-level) cache misses**: data that must be fetched from RAM, this
   can take 100+ cycles

The total number of cycles is calculated like this:

$$
\text{cycles} \approx \text{Icycles} + (\text{L1 Misses} \times \text{L2/L3 Cost}) + (\text{LL Misses} \times \text{RAM Cost})
$$

> [accordion] How are executed instruction cycles weighted?
>
> Each executed instruction is charged a cost based on measured cost data for real
> CPUs, so expensive instructions count for more than cheap ones:
>
> ```asm theme={null}
> imul rax, rbx  ; a few cycles
> div rbx        ; ~20-30 cycles
> ```
>
> This weighting is what makes the estimate track real hardware. Charging every
> instruction the same cost would report replacing a `div` with a multiply as
> almost no change, even though it is significantly faster in practice.
>
> For background on how per-instruction latency and throughput are measured, see
> the
> [Agner Fog instruction tables](https://www.agner.org/optimize/instruction_tables.pdf)
> and [uops.info](https://www.uops.info).

### Converting Cycles to Time

Once we have the number of cycles for a benchmark, we transform it into an
execution time measurement by using the following formula, where `FREQUENCY` is
a constant set to the frequency (number of instructions executed per second) of
a real CPU:

$$
execution\_time = \frac{cycles}{FREQUENCY}
$$

We then calculate the **execution speed** of the benchmark by taking the inverse
of the execution time:

$$
speed = \frac{1}{execution\_time}
$$

This is the displayed metric in the CodSpeed reports.

> [!NOTE]
>
> **Why choose execution speed over execution time?**
>
> A performance increase of a benchmark will increase its execution speed. Same
> for a performance regression. However, if execution time was used, a performance
> increase of a benchmark would result in a decrease in its execution time. This
> would be counter-intuitive.

### System Calls

System calls play a critical role in the performance of software, but they
present unique challenges for accurate measurement. **A system call is a request
made by a program to the operating system's kernel**, typically for I/O
operations such as reading from or writing to files, communicating over a
network, or interacting with hardware devices.

Due to their nature, **system calls introduce variability in execution time**.
This variability is influenced by several factors, including system load,
network latency, and disk I/O performance. As a result, the execution time of
system calls can fluctuate significantly, making them the most inconsistent part
of a program's execution time.

To ensure that our execution speed measurements are as stable and reliable as
possible, **CodSpeed CPU Simulation mode does not include system calls in the
measurement**. Instead, we focus solely on the code executed within user
space(the code you wrote), excluding any time spent in system calls. This
approach allows us to provide a clear and consistent metric for the execution
speed of your code, independent of your hardware and all variability that it can
create.

> [!TIP]
>
> **Walltime measurement with CodSpeed Macro Runners**
>
> If the code you wish to optimize and measure relies heavily on system calls, you
> can use CodSpeed Macro Runners combined with our Walltime instrument. You can
> find more information in the [Walltime](https://codspeed.io/docs/instruments/walltime.md) section of the
> docs.

Still, **the walltime spent on system calls is recorded and this data is
available in the trace view**, providing insight into how much time is consumed
by system interactions. While these times are not included in the overall
execution speed metric, they offer valuable information for performance
analysis.

> [!NOTE]
>
> **Roadmap for system calls**
>
> In the future, we plan to enhance CodSpeed by emulating system calls. This will
> allow us to more accurately anticipate the performance impact of system calls,
> further improving the reliability and comprehensiveness of our performance
> measurements.

## Legacy Terminology

Previously, this instrument was referred to as "instrumentation" or
"instrumentation mode".

This terminology is being phased out in favor of "CPU simulation" to better
reflect what the instrument does: simulating CPU behavior. While the old
`instrumentation` value is still accepted for backward compatibility, it will be
removed in a future release.

We recommend updating your configuration and your integration library to use
`simulation` instead.

> [!NOTE]
>
> Going forward, what we will refer to as **"instrumentation"** represents the
> generic overlay that CodSpeed applies to your benchmarks to collect
> performance data and profiling information.
>
> It applies to both CPU Simulation and Walltime instruments.

## Automated Profiling

When using the CPU simulation instrument, CodSpeed automatically collects
[profiling data and generates flamegraphs](https://codspeed.io/docs/features/profiling.md) for each
benchmark when available. This allows you to quickly identify performance
bottlenecks and their root causes.

### Inspector Metrics

When you hover over a span in the flamegraph, the inspector displays CPU
simulation-specific metrics:

![Flamegraph inspector](https://mintcdn.com/codspeed/J_9QffCKgr3Hbs6D/instruments/cpu/assets/tooltip-explanation.excalidraw.png?fit=max\&auto=format\&n=J_9QffCKgr3Hbs6D\&q=85\&s=207eebeeb34900a7d27eed74c14c9b20)

* **Self time**: The simulated execution time spent in the function body only,
  excluding time spent in child function calls.

* **Total time**: The simulated execution time spent in the function including
  all its children.

The time bars are broken down into components that show what is limiting
progress:

* **Instructions**: Time spent executing CPU instructions.
* **Cache**: Time spent due to CPU cache misses (L1, L2, L3).
* **Memory**: Time spent waiting for main memory access.

This breakdown helps you identify whether a function is instruction-bound,
cache-bound, or memory-bound, guiding your optimization efforts.

## Compatibility

To enable profiling with the CPU simulation instrument, ensure you meet the
following minimum version requirements:

| Language | Minimum required versions |
| :- | :- |
| [Python](https://codspeed.io/docs/benchmarks/python.md) | Python 3.12+ and [`pytest-codspeed>=2.0.0`](https://github.com/CodSpeedHQ/pytest-codspeed/releases/tag/v2.0.0) |
| [Rust](https://codspeed.io/docs/benchmarks/rust.md) | Any version of [`codspeed-divan-compat`](https://github.com/CodSpeedHQ/codspeed-rust/releases/tag/v2.8.0) or [`codspeed-criterion-compat`](https://github.com/CodSpeedHQ/codspeed-rust/releases/tag/v2.9.1) |
| [C++](https://codspeed.io/docs/benchmarks/cpp.md) | Any version of [`codspeed-google-benchmark`](https://github.com/CodSpeedHQ/codspeed-cpp/releases/tag/v1.0.0) |
| [Node.js](https://codspeed.io/docs/benchmarks/nodejs/overview.md) | A [supported Node.js version](https://codspeed.io/docs/benchmarks/nodejs/overview.md#supported-node-js-versions), plus [`@codspeed/vitest-plugin>=2.3.1`](https://github.com/CodSpeedHQ/codspeed-node/releases/tag/v2.3.1), [`@codspeed/tinybench-plugin>=2.2.0`](https://github.com/CodSpeedHQ/codspeed-node/releases/tag/v2.2.0), or [`@codspeed/benchmark.js-plugin>=2.2.0`](https://github.com/CodSpeedHQ/codspeed-node/releases/tag/v2.2.0) |

[Go](https://codspeed.io/docs/benchmarks/go.md) and [Java](https://codspeed.io/docs/benchmarks/java.md) benchmarks only support the
[walltime instrument](https://codspeed.io/docs/instruments/walltime.md#compatibility).

## Usage with GitHub Actions

To enable CPU Simulation in your GitHub Actions workflow, ensure you are using
`mode: simulation` in the CodSpeed Action configuration.

```yaml highlight={16} theme={null}
jobs:
  benchmarks:
    name: Run benchmarks
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      # ...
      # Setup your environment here:
      #  - Configure your Python/Rust/Node version
      #  - Install your dependencies
      #  - Build your benchmarks (if using a compiled language)
      # ...
      - name: Run the benchmarks
        uses: CodSpeedHQ/action@v5
        with:
          mode: simulation
          run: <Insert your benchmark command here>
```

## Next Steps

> [card] [Profiling](https://codspeed.io/docs/features/profiling.md)
>
> Learn how to read flamegraphs and use profiling to optimize your code

> [card] [Unexpected Regressions](https://codspeed.io/docs/instruments/cpu/regression-causes.md)
>
> Understand why benchmarks can regress without code changes

> [card] [Walltime Instrument](https://codspeed.io/docs/instruments/walltime.md)
>
> Measure real-world execution time including system calls and I/O


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.