PluginWorks in Claude CodeCurrent
Codspeed
CodSpeed is the all-in-one performance testing toolkit. Dive into benchmarking results, flamegraphs, and performance comparisons — give Claude granular profiling context to pinpoint bottlenecks and autonomously iterate on performance via the CodSpeed MCP server.
0
Try it
See what this would do for you. No sign-up needed.
Install in Claude Code
Run these in Claude Code, in order. The first adds the marketplace, the second installs the plugin.
Step 1
/plugin marketplace add anthropics/claude-plugins-official
Step 2
/plugin install codspeed@claude-plugins-official
Review commands before running them. Promptu never runs code on your machine or pushes changes to your repo.
What's inside
2 skills
- codspeed-optimize
- codspeed-setup-harness
1 MCP server
Security scan
Flagged
Promptu's text scan flagged something in this plugin. Read its files before you install it.
pipe-to-shell in README.md:41
Details
<p align="center">
<a href="https://codspeed.io/?utm_source=codspeed&utm_medium=readme">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/codspeed-logo-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/codspeed-logo-light.svg">
<img alt="CodSpeed logo" src="https://codspeed.io/codspeed-logo-light.svg" width="400px">
</picture>
</a>
</p>
<h3 align="center">Optimize code performance and catch regressions early.</h3>
<p align="center"><a href="https://codspeed.io/login?flow=get-started&utm_source=github-readme">Get Started</a> · <a href="https://codspeed.io/docs?utm_source=github-readme">Documentation</a></p>
<br/>
<p align="center">
<a href="https://github.com/CodSpeedHQ/codspeed/releases/latest"><img src="https://img.shields.io/github/v/release/CodSpeedHQ/codspeed" alt="Latest Release"></a>
<a href="https://github.com/CodSpeedHQ/codspeed/releases"><img src="https://img.shields.io/github/downloads/CodSpeedHQ/codspeed/total?logo=github" alt="Downloads"></a>
<a href="https://github.com/CodSpeedHQ/codspeed/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/CodSpeedHQ/codspeed/ci.yml?branch=main&logo=github&label=CI" alt="CI Status"></a>
<a href="https://github.com/CodSpeedHQ/codspeed/blob/main/LICENSE-APACHE"><img src="https://img.shields.io/github/license/CodSpeedHQ/codspeed" alt="License"></a>
<a href="https://codspeed.io/discord"><img src="https://img.shields.io/badge/chat%20on-discord-7289da.svg" alt="Discord Chat"></a>
<a href="https://codspeed.io/?utm_source=badge"><img src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" alt="CodSpeed Badge"></a>
</p>
[](https://codspeed.io/?utm_source=github-readme)
# Key features
- 🎯 **<1% variance** in measurements using CPU simulation - no more flaky benchmarks.
- 🔥 **Differential flamegraphs** to pinpoint exactly what got slower, commit by commit.
- 💬 **PR comments & status checks** showing performance impact directly in your workflow.
- 🛡️ **Merge protection** to block PRs that degrade performance beyond your threshold.
- 🐍 **Multi-language support** for Python, Rust, Node.js, Go, C/C++ and more.
- 🏠 **Run locally or in CI** - works on your machine and integrates with GitHub Actions, GitLab CI, CircleCI, and more.
- 🔌 **Plug your existing benchmarks** in less than 5 minutes - works with pytest, vitest, criterion, and more.
## Installation
```bash
curl -fsSL https://codspeed.io/install.sh | bash
```
> [!NOTE]
> The CodSpeed CLI officially supports Ubuntu 20.04, 22.04, 24.04 and Debian 11, 12.
> Other Linux distributions may work, but are not officially supported.
## Quick Start
First, authenticate to keep your benchmark results linked to your CodSpeed account:
```bash
codspeed auth login
```
The simplest way to get started is to benchmark any executable program directly:
```bash
# Benchmark a single command
codspeed exec -- ./my-binary --arg1 value
# Benchmark a script
codspeed exec -- python my_script.py
# Benchmark with specific instrument
codspeed exec --mode walltime -- node app.js
```
This approach requires no code changes and works with any executable. CodSpeed will measure the performance provide the instrument results.
## Deeper integration with harnesses using `codspeed run`
For more control and integration with your existing benchmark suite, you can use language-specific harnesses. This allows you to:
- Define multiple benchmarks and keep them versioned in your codebase
- Scope benchmarks to specific functions or modules
- Integrate with existing benchmark suites (pytest, criterion, vitest, etc.)
```bash
# Using the Rust harness with criterion
codspeed run cargo codspeed run
# Using the Python harness with pytest
codspeed run pytest ./tests --codspeed
# Using the Node.js harness with vitest
codspeed run pnpm vitest bench
```
These harnesses provide deeper instrumentation and allow you to write benchmarks using familiar testing frameworks.
### Languages Integrations
CodSpeed provides first-class integrations for multiple languages and frameworks:
| Language | Repository | Supported Frameworks |
| --------------- | ---------------------------------------------------------------- | ------------------------------------- |
| Rust | [codspeed-rust](https://github.com/CodSpeedHQ/codspeed-rust) | `divan`, `criterion.rs`, `bencher` |
| C/C++ | [codspeed-cpp](https://github.com/CodSpeedHQ/codspeed-cpp) | `google-benchmark` |
| Python | [pytest-codspeed](https://github.com/CodSpeedHQ/pytest-codspeed) | `pytest` plugin |
| Node.js | [codspeed-node](https://github.com/CodSpeedHQ/codspeed-node) | `vitest`, `tinybench`, `benchmark.js` |
| Go | [codspeed-go](https://github.com/CodSpeedHQ/codspeed-go) | builtin `testing` package integration |
| Zig (community) | [codspeed-zig](https://github.com/james-elicx/codspeed-zig) | custom |
Need to bench another language or framework? Open [an issue](https://github.com/CodSpeedHQ/codspeed/issues) or let us know on [Discord](https://codspeed.io/discord)!
### CLI Harness: `codspeed.yml` configuration
The CLI also offers a built-in harness that allows you to define benchmarks directly.
You can define multiple `codspeed exec` benchmark targets and configure options in a `codspeed.yml` file.
This is useful when you want to benchmark several commands with different configurations.
Create a `codspeed.yml` file in your project root:
```yaml
# Global options applied to all benchmarks
options:
warmup-time: "0.2s"
max-time: 1s
# List of benchmarks to run
benchmarks:
- name: "Fast operation"
exec: ./my_binary --mode fast
options:
max-rounds: 20
- name: "Slow operation"
exec: ./my_binary --mode slow
options:
max-time: 200ms
- name: "Script benchmark"
exec: python scripts/benchmark.py
```
Then run all benchmarks with:
```bash
codspeed run --mode walltime
```
> [!TIP]
> For more details on configuration options, see the [CLI documentation](https://codspeed.io/docs/cli).
## Performance Instruments
CodSpeed provides multiple instruments to measure different aspects of your code's performance. Choose the one that best fits your use case:
### CPU Simulation
Simulates CPU behavior for **<1% variance** regardless of system load. Hardware-agnostic measurements with automatic flame graphs.
**Best for:** CPU-intensive code, CI regression detection, cross-platform comparison
```bash
codspeed exec --mode simulation -- ./my-binary
```
### Memory
Tracks heap allocations (peak usage, count, allocation size) with eBPF profiling.
**Best for:** Memory optimization, leak detection, constrained environments
**Supported:** Rust, C/C++ with libc, jemalloc, mimalloc
```bash
codspeed exec --mode memory -- ./my-binary
```
### Walltime
Measures real-world execution time including I/O, system calls, and multi-threading effects.
**Best for:** API tests, I/O-heavy workloads, multi-threaded applications
```bash
codspeed exec --mode walltime -- ./my-api-test
```
> [!WARNING]
> Using the `walltime` mode on traditional VMs/Hosted Runners will lead to inconsistent data. For the best results, we recommend using CodSpeed Hosted Macro Runners, which are fine-tuned for performance measurement consistency.
> Check out the [Walltime Instrument Documentation](https://docs.codspeed.io/instruments/walltime/) for more details.
> [!TIP]
> For detailed information on each instrument, see the [Instruments documentation](https://codspeed.io/docs/instruments).
## Usage In CI environments
Running CodSpeed in CI allows you to automatically detect performance regressions on every pull request and track performance evolution over time.
### GitHub Actions
We recommend using our official GitHub Action: [@CodSpeedHQ/action](https://github.com/CodSpeedHQ/action).
Here is a sample `.github/workflows/codspeed.yml` workflow for Python:
```yaml
name: CodSpeed Benchmarks
on:
push:
branches:
- "main" # or "master"
pull_request:
workflow_dispatch:
permissions:
contents: read
id-token: write
jobs:
benchmarks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# Set up your language/environment here
# For Python:
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt
# Run benchmarks with CodSpeed
- uses: CodSpeedHQ/action@v5
with:
mode: instrumentation
run: pytest tests/ --codspeed
```
### GitLab CI
Here is a sample `.gitlab-ci.yml` configuration for Python:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
codspeed:
stage: test
image: python:3.12
id_tokens:
CODSPEED_TOKEN:
aud: codspeed.io
before_script:
- pip install -r requirements.txt
- curl -fsSL https://codspeed.io/install.sh | bash -s -- --quiet
script:
- codspeed run --mode simulation -- pytest tests/ --codspeed
```
### CircleCI
CodSpeed supports CircleCI for repositories hosted on GitHub.
Here is a sample `.circleci/config.yml` configuration for Python:
```yaml
version: 2.1
jobs:
benchmarks:
docker:
- image: cimg/python:3.12
steps:
- checkout
- run: pip install -r requirements.txt
- run: curl -fsSL https://codspeed.io/install.sh | bash -s -- --quiet
- run: codspeed run --mode simulation -- pytest tests/ --codspeed
workflows:
codspeed:
jobs:
- benchmarks
```
Jobs authenticate with OpenID Connect (OIDC) automatically, so there is no token to store. Pull requests opened from a fork cannot mint an OIDC token: set the `CODSPEED_TOKEN` environment variable for those jobs, as described in the [CircleCI configuration documentation](https://codspeed.io/docs/integrations/ci/circleci/configuration).
> [!TIP]
> For more CI integration examples and advanced configurations, check out the [CI Integration Documentation](https://codspeed.io/docs/integrations/ci/).
## skills/codspeed-optimize/SKILL.md
---
name: codspeed-optimize
description: "Autonomously optimize code for performance using CodSpeed benchmarks, flamegraph analysis, and iterative improvement. Use this skill whenever the user wants to make code faster, reduce CPU usage, optimize memory, improve throughput, find performance bottlenecks, or asks to 'optimize', 'speed up', 'make faster', 'reduce latency', 'improve performance', or points at a CodSpeed benchmark result wanting improvements. Also trigger when the user mentions a slow function, a regression, or wants to understand where time is spent in their code."
---
# Optimize
You are an autonomous performance engineer. Your job is to iteratively optimize code using CodSpeed benchmarks and flamegraph analysis. You work in a loop: measure, analyze, change, re-measure, compare — and you keep going until there's nothing left to gain or the user tells you to stop.
**All measurements must go through CodSpeed.** Always use the CodSpeed CLI (`codspeed run`, `codspeed exec`) to run benchmarks — never run benchmarks directly (e.g., `cargo bench`, `pytest-benchmark`, `go test -bench`) outside of CodSpeed. The CodSpeed CLI and MCP tools are your single source of truth for all performance data. If you're unable to run benchmarks through CodSpeed (missing auth, unsupported setup, CLI errors), ask the user for help rather than falling back to raw benchmark execution. Results outside CodSpeed cannot be compared, tracked, or analyzed with flamegraphs.
## Before you start
1. **Understand the target**: What code does the user want to optimize? A specific function, a whole module, a benchmark suite? If unclear, ask.
2. **Understand the metric**: CPU time (default), memory, walltime? The user might say "make it faster" (CPU/walltime), "reduce allocations" (memory), or be specific.
3. **Check for existing benchmarks**: Look for benchmark files, `codspeed.yml`, or CI workflows. **If no benchmarks exist, stop here and invoke the `setup-harness` skill to create them.** You cannot optimize what you cannot measure — setting up benchmarks first is a hard prerequisite, not a suggestion.
4. **Check CodSpeed auth**: Run `codspeed auth login` if needed. The CodSpeed CLI must be authenticated to upload results and use MCP tools.
## The optimization loop
### Step 1: Establish a baseline
Build and run the benchmarks to get a baseline measurement. Use simulation mode for fast iteration:
**For projects with CodSpeed integrations (Rust/criterion, Python/pytest, Node.js/vitest, etc.):**
```bash
# Build with CodSpeed instrumentation
cargo codspeed build -m simulation # Rust
# or for other languages, benchmarks run directly
# Run benchmarks
codspeed run -m simulation -- <bench_command>
```
**For projects using the exec harness or codspeed.yml:**
```bash
codspeed run -m simulation
# or
codspeed exec -m simulation -- <command>
```
**Scope your runs**: When iterating on a specific area, run only the relevant benchmarks. This dramatically speeds up the feedback loop:
```bash
# Rust: build and run only relevant suite
cargo codspeed build -m simulation --bench decode
codspeed run -m simulation -- cargo codspeed run --bench decode cat.jpg
# codspeed.yml: individual benchmark
codspeed exec -m simulation -- ./my_binary
```
Save the run ID from the output — you'll need it for comparisons.
### Step 2: Analyze with flamegraphs
Use the CodSpeed MCP tools to understand where time is spent:
1. **List runs** to find your baseline run ID:
- Use `list_runs` with appropriate filters (branch, event type)
2. **Query flamegraphs** on the hottest benchmarks with `query_flamegraph`:
- Start from the whole flame graph to get the big picture, then re-root into the hottest subtrees to zoom in
- Look for:
- Functions with high **self time** (these are the actual bottlenecks)
- Instruction-bound vs cache-bound vs memory-bound breakdown
- Unexpected functions appearing high in the profile (redundant work, unnecessary abstractions)
3. **Identify optimization targets**: Rank functions by self time. The top 2-3 are your targets. Consider:
- Can this computation be avoided entirely?
- Can the algorithm be improved (O(n) vs O(n^2))?
- Are there unnecessary allocations in hot loops?
- Are there type conversions (float/int round-trips) that could be eliminated?
- Could data layout be improved for cache locality?
- Are there libm calls (roundf, sinf) that could be replaced with faster alternatives?
- Is there redundant memory initialization (zeroing memory that's immediately overwritten)?
### Step 3: Make targeted changes
Apply optimizations one at a time. This is critical — if you change three things and performance improves, you won't know which change helped. If it regresses, you won't know which one hurt.
**Important constraints:**
- Only change code you've read and understood
- Preserve correctness — run existing tests after each change
- Keep changes minimal and focused
- Don't over-engineer — the simplest fix that works is the best fix
**Common optimization patterns by bottleneck type:**
- **Instruction-bound**: Algorithmic improvements, loop unrolling, removing redundant computations, SIMD
- **Cache-bound**: Improve data locality, reduce struct size, use contiguous memory, avoid pointer chasing
- **Memory-bound**: Reduce allocations, reuse buffers, avoid unnecessary copies, use stack allocation
- **System-call-bound**: Batch I/O, reduce file operations, buffer writes (note: simulation mode doesn't measure syscalls, use walltime for these)
### Step 4: Re-measure and compare
After each change, rebuild and rerun the relevant benchmarks:
```bash
# Rebuild and rerun (scoped to what you changed)
cargo codspeed build -m simulation --bench <suite>
codspeed run -m simulation -- cargo codspeed run --bench <suite>
```
Then compare against the baseline using the MCP tools:
- Use `compare_runs` with `base_run_id` (baseline) and `head_run_id` (after your change)
- Check for:
- **Improvements** in your target benchmarks
- **Regressions** in other benchmarks (shared code paths can affect unrelated benchmarks)
- The magnitude of the change — is it significant?
### Step 5: Report and decide next steps
**When you find a significant improvement** (>5% on target benchmarks with no regressions), pause and tell the user:
- What you changed and why
- The before/after numbers from `compare_runs`
- What the flamegraph showed as the bottleneck
- What further optimizations you see as possible next steps
Then ask if they want you to continue optimizing or if they're satisfied.
**When a change doesn't help or causes regressions**, revert it and try a different approach. Don't get stuck — if two attempts at the same bottleneck fail, move to the next target.
### Step 6: Validate with walltime
Before finalizing any optimization, always validate with walltime benchmarks. Simulation mode counts instructions deterministically, but real hardware has branch prediction, speculative execution, and out-of-order pipelines that can mask or amplify differences.
```bash
# Build for walltime
cargo codspeed build -m walltime # Rust with cargo-codspeed
# or just run directly for other setups
# Run with walltime
codspeed run -m walltime -- <bench_command>
# or
codspeed exec -m walltime -- <command>
```
Then compare the walltime run against a walltime baseline using `compare_runs`.
**Patterns that often show up in simulation but NOT walltime:**
- Iterator adapter overhead (e.g., `.take(n)` to `[..n]`) — branch prediction hides it
- Bounds check elimination — hardware speculates past them
- Trivial arithmetic simplifications — hidden by out-of-order execution
**Patterns that reliably help in both modes:**
- Avoiding type conversions in hot loops (float/integer round-trips)
- Eliminating libm calls (roundf, sinf — these are software routines)
- Skipping redundant memory initialization
- Algorithmic improvements (reducing overall work)
If a simulation improvement doesn't show up in walltime, strongly consider reverting it — the added code complexity isn't worth a phantom improvement.
### Step 7: Continue or finish
If the user wants more optimization, go back to Step 2 with fresh flamegraphs from your latest run. The profile will have shifted now that you've addressed the top bottleneck, revealing new targets.
Keep iterating until:
- The user says they're satisfied
- The flamegraph shows no clear bottleneck (time is spread evenly)
- Remaining optimizations would require architectural changes the user hasn't approved
- You've hit diminishing returns (<1-2% improvement per change)
## Language-specific notes
### Rust
- Use `cargo codspeed build -m <mode>` to build, `cargo codspeed run` to run
- `--bench <name>` selects specific benchmark suites (matching `[[bench]]` targets in Cargo.toml)
- Positional filter after `cargo codspeed run` matches benchmark names (e.g., `cargo codspeed run cat.jpg`)
- Frameworks: criterion, divan, bencher (all work with cargo-codspeed)
### Python
- Uses pytest-codspeed: `codspeed run -m simulation -- pytest --codspeed`
- Framework: pytest-benchmark compatible
### Node.js
- Frameworks: vitest (`@codspeed/vitest-plugin`), tinybench v5 (`@codspeed/tinybench-plugin`), benchmark.js (`@codspeed/benchmark.js-plugin`)
- Run via: `codspeed run -m simulation -- npx vitest bench` (or equivalent)
### Go
- Built-in: `codspeed run -m simulation -- go test -bench .`
- No special packages needed — CodSpeed instruments `go test -bench` directly
### C/C++
- Uses Google Benchmark with valgrind-codspeed
- Build with CMake, run benchmarks via `codspeed run`
### Any language (exec harness)
- Use `codspeed exec -m <mode> -- <command>` for any executable
- Or define benchmarks in `codspeed.yml` and use `codspeed run`
- No code changes required — CodSpeed instruments the binary externally
## MCP tools
You have access to the CodSpeed MCP tools. Their live schemas are the source of truth for each tool's exact name, parameters, and behavior; read the parameters there and don't assume any beyond what a tool declares. How to use them for this task:
- **`compare_runs`** is your primary tool for measuring impact: it reports the improvements, regressions, and new/missing benchmarks between two runs.
- **`query_flamegraph`** shows where time is spent. Use it to find the real hot path — often not where you'd guess — before changing anything, and to zoom into a specific function or thread.
- **`list_runs`**, **`get_run`**, and **`list_repositories`** cover run and repository lookups — use them to find your baseline and latest run IDs, and the repository slug if needed.
## Guiding principles
- **Everything goes through CodSpeed.** Never run benchmarks outside of the CodSpeed CLI. Never quote timing numbers from raw benchmark output. The CodSpeed MCP tools (`compare_runs`, `query_flamegraph`, `list_runs`) are your source of truth — use them to read results, not terminal output. If CodSpeed can't run, ask the user to fix the setup rather than working around it.
- **Measure first, optimize second.** Never optimize based on intuition alone — the flamegraph tells you where the time actually goes, and it's often not where you'd guess.
- **One change at a time.** Isolated changes make it clear what helped and what didn't.
- **Correctness over speed.** Always run tests. A fast but broken program is useless.
- **Simulation for iteration, walltime for validation.** Simulation is deterministic and fast for feedback. Walltime is the ground truth. Both run through CodSpeed.
- **Know when to stop.** Diminishing returns are real. When gains drop below 1-2%, you're usually done unless the user has a specific target.
- **Be transparent.** Show the user your reasoning, the numbers, and the tradeoffs. Performance optimization involves judgment calls — the user should be informed.
## skills/codspeed-setup-harness/SKILL.md
---
name: codspeed-setup-harness
description: "Set up performance benchmarks and CodSpeed harness for a project. Use this skill whenever the user wants to create benchmarks, add performance tests, set up CodSpeed, configure codspeed.yml, integrate a benchmarking framework (criterion, divan, pytest-benchmark, vitest bench, go test -bench, google benchmark), or when the user says 'add benchmarks', 'set up perf tests', 'create a benchmark', 'benchmark this', or wants to measure performance of their code for the first time. Also trigger when the optimize skill needs benchmarks that don't exist yet."
---
# Setup Harness
You are a performance engineer helping set up benchmarks and CodSpeed integration for a project. Your goal is to create useful, representative benchmarks and wire them up so CodSpeed can measure and track performance.
## Step 1: Analyze the project
Before writing any benchmark code, understand what you're working with:
1. **Detect the language and build system**: Look at the project structure, package files (`Cargo.toml`, `package.json`, `pyproject.toml`, `go.mod`, `CMakeLists.txt`), and source files.
2. **Identify existing benchmarks**: Check for benchmark files, `codspeed.yml`, CI workflows mentioning CodSpeed or benchmarks.
3. **Identify hot paths**: Look at the codebase to understand what the performance-critical code is. Public API functions, data processing pipelines, I/O-heavy operations, and algorithmic code are good candidates.
4. **Check CodSpeed auth**: Ensure `codspeed auth login` has been run.
## Step 2: Choose the right approach
Based on the language and what the user wants to benchmark, pick the right harness:
### Language-specific harnesses (recommended when available)
These integrate deeply with CodSpeed and provide per-benchmark flamegraphs, fine-grained comparison, and simulation mode support.
| Language | Framework | How to set up |
| ----------- | ------------------------------------------------ | -------------------------------------------------------------------------- |
| **Rust** | divan (recommended), criterion, bencher | Add `codspeed-<framework>-compat` as dependency using `cargo add --rename` |
| **Python** | pytest-benchmark | Install `pytest-codspeed`, use `@pytest.benchmark` or `benchmark` fixture |
| **Node.js** | vitest (recommended), tinybench v5, benchmark.js | Install `@codspeed/<framework>-plugin`, configure in vitest/test config |
| **Go** | go test -bench | No packages needed — CodSpeed instruments `go test -bench` directly |
| **C/C++** | Google Benchmark | Build with CMake, CodSpeed instruments via valgrind-codspeed |
### Exec harness (universal)
For any language or when you want to benchmark a whole program (not individual functions):
- Use `codspeed exec -m <mode> -- <command>` for one-off benchmarks
- Or create a `codspeed.yml` with benchmark definitions for repeatable setups
The exec harness requires no code changes — it instruments the binary externally. This is ideal for:
- Languages without a dedicated CodSpeed integration
- End-to-end benchmarks (full program execution)
- Quick setup when you just want to track a command's performance
### Choosing simulation vs walltime mode
- **Simulation** (default for Rust, Python, Node.js, C/C++): Deterministic CPU simulation, <1% variance, automatic flamegraphs. Best for CPU-bound code. Does not measure system calls or I/O.
- **Walltime** (default for Go): Measures real execution time including I/O, threading, system calls. Best for I/O-heavy or multi-threaded code. Requires consistent hardware (use CodSpeed Macro Runners in CI).
- **Memory**: Tracks heap allocations. Best for reducing memory usage. Supported for Rust, C/C++ with libc/jemalloc/mimalloc.
## Step 3: Set up the harness
### Rust with divan (recommended)
1. Add the dependency:
```bash
cargo add divan
cargo add codspeed-divan-compat --rename divan --dev
```
2. Create a benchmark file in `benches/`:
```rust
// benches/my_bench.rs
use divan;
fn main() {
divan::main();
}
#[divan::bench]
fn bench_my_function() {
// Call the function you want to benchmark
// Use divan::black_box() to prevent compiler optimization
divan::black_box(my_crate::my_function());
}
```
3. Add to `Cargo.toml`:
```toml
[[bench]]
name = "my_bench"
harness = false
```
4. Build and run:
```bash
cargo codspeed build -m simulation --bench my_bench
codspeed run -m simulation -- cargo codspeed run --bench my_bench
```
### Rust with criterion
1. Add dependencies:
```bash
cargo add criterion --dev
cargo add codspeed-criterion-compat --rename criterion --dev
```
2. Create benchmark in `benches/`:
```rust
use criterion::{criterion_group, criterion_main, Criterion};
fn bench_my_function(c: &mut Criterion) {
c.bench_function("my_function", |b| {
b.iter(|| my_crate::my_function())
});
}
criterion_group!(benches, bench_my_function);
criterion_main!(benches);
```
3. Add to `Cargo.toml` and build/run same as divan.
### Python with pytest-codspeed
1. Install:
```bash
pip install pytest-codspeed
# or
uv add --dev pytest-codspeed
```
2. Create benchmark tests:
```python
# tests/test_benchmarks.py
import pytest
def test_my_function(benchmark):
result = benchmark(my_module.my_function, arg1, arg2)
# You can still assert on the result
assert result is not None
# Or using the pedantic API for setup/teardown:
def test_with_setup(benchmark):
data = prepare_data()
benchmark.pedantic(my_module.process, args=(data,), rounds=100)
```
3. Run:
```bash
codspeed run -m simulation -- pytest --codspeed
```
### Node.js with vitest (recommended)
1. Install:
```bash
npm install -D @codspeed/vitest-plugin
# or
pnpm add -D @codspeed/vitest-plugin
```
2. Configure vitest (`vitest.config.ts`):
```typescript
import { defineConfig } from "vitest/config";
import codspeed from "@codspeed/vitest-plugin";
export default defineConfig({
plugins: [codspeed()],
});
```
3. Create benchmark file:
```typescript
// bench/my.bench.ts
import { bench, describe } from "vitest";
describe("my module", () => {
bench("my function", () => {
myFunction();
});
});
```
4. Run:
```bash
codspeed run -m simulation -- npx vitest bench
```
### Go
No packages needed — CodSpeed instruments `go test -bench` directly.
1. Create benchmark tests:
```go
// my_test.go
func BenchmarkMyFunction(b *testing.B) {
for i := 0; i < b.N; i++ {
MyFunction()
}
}
```
2. Run (walltime is the default for Go):
```bash
codspeed run -m walltime -- go test -bench . ./...
```
### C/C++ with Google Benchmark
1. Install Google Benchmark (via CMake FetchContent or system package)
2. Create benchmark:
```cpp
#include <benchmark/benchmark.h>
static void BM_MyFunction(benchmark::State& state) {
for (auto _ : state) {
MyFunction();
}
}
BENCHMARK(BM_MyFunction);
BENCHMARK_MAIN();
```
3. Build and run with CodSpeed:
```bash
cmake -B build && cmake --build build
codspeed run -m simulation -- ./build/my_benchmark
```
### Exec harness (any language)
For benchmarking whole programs without code changes:
1. Create `codspeed.yml`:
```yaml
$schema: https://raw.githubusercontent.com/CodSpeedHQ/codspeed/refs/heads/main/schemas/codspeed.schema.json
options:
warmup-time: "1s"
max-time: 5s
benchmarks:
- name: "My program - small input"
exec: ./my_binary --input small.txt
- name: "My program - large input"
exec: ./my_binary --input large.txt
options:
max-time: 30s
```
2. Run:
```bash
codspeed run -m walltime
```
Or for a one-off:
```bash
codspeed exec -m walltime -- ./my_binary --input data.txt
```
## Step 4: Write good benchmarks
Good benchmarks are representative, isolated, and stable. Here are guidelines:
- **Benchmark real workloads**: Use realistic input data and sizes. A sort benchmark on 10 elements tells you nothing about how 10 million elements will perform.
- **Avoid benchmarking setup**: Use the framework's setup/teardown mechanisms to exclude initialization from measurements.
- **Prevent dead code elimination**: Use `black_box()` (Rust), `benchmark::DoNotOptimize` (C++), or `Blackhole.consume` (JMH) so the compiler doesn't optimize away unused results.
- **Cover the critical path**: Benchmark the functions that matter most to your users — the ones called frequently or on the hot path.
- **Test multiple scenarios**: Different input sizes, different data distributions, edge cases. Performance characteristics often change with scale.
- **Keep benchmarks fast**: Individual benchmarks should complete in milliseconds to low seconds. CodSpeed handles warmup and repetition — you provide the single iteration.
## Step 5: Verify and run
After setting up:
1. **Run the benchmarks locally** to verify they work:
```bash
# For language-specific harnesses
cargo codspeed build -m simulation && codspeed run -m simulation -- cargo codspeed run
# or
codspeed run -m simulation -- pytest --codspeed
# or
codspeed run -m simulation -- npx vitest bench
# etc.
# For exec harness
codspeed run -m walltime
```
2. **Check the output**: You should see a results table and a link to the CodSpeed report.
3. **Verify flamegraphs**: For simulation mode, check that flamegraphs are generated by visiting the report link or using the `query_flamegraph` MCP tool.
4. **Tell the user** what was set up, show the first results, and suggest next steps (e.g., adding CI integration, running the `optimize` skill).

