> ## 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.

# Running Benchmarks in GitHub Actions

> Learn how to setup CodSpeed and run benchmarks within your GitHub Actions CI workflow

export const CIWorkflow = ({minimal = false, enableWorkflowDispatch = true, runsOn = "ubuntu-latest", highlight = [], mode, modes, submodules = false, preSteps = [], buildSteps = ["# ...", "# Setup your environment here:", "#  - Configure your Python/Rust/Node version", "#  - Install your dependencies", "#  - Build your benchmarks (if using a compiled language)", "# ..."], benchmarkCommand = ["<Insert your benchmark command here>"], jobName = "Run benchmarks", env = {}}) => {
  const modeList = modes || (mode ? [mode] : undefined);
  if (!modeList || modeList.length === 0) {
    throw new Error("mode or modes is required");
  }
  const indent = (lines, depth) => {
    const reindentedLines = lines.map(l => l.length === 0 ? l : (" ").repeat(depth) + l);
    return reindentedLines.join("\n");
  };
  const workflowDispatchSection = enableWorkflowDispatch ? "  # `workflow_dispatch` allows CodSpeed to trigger backtest\n" + "  # performance analysis in order to generate initial data.\n" + "  workflow_dispatch:\n" : "";
  let yaml = "";
  if (!minimal) {
    yaml += `
name: CodSpeed Benchmarks

on:
  push:
    branches:
      - "main" # or "master"
  pull_request:
`;
    yaml += workflowDispatchSection;
  }
  yaml += `
jobs:
  benchmarks:
    name: ${jobName}
    runs-on: ${runsOn}`;
  if (!minimal) {
    yaml += `
    permissions: # optional for public repositories
      contents: read # required for actions/checkout
      id-token: write # required for OIDC authentication with CodSpeed`;
  }
  if (preSteps.length > 0) yaml += "\n" + indent(preSteps, 4);
  yaml += `
    steps:
      - uses: actions/checkout@v5`;
  if (submodules) {
    const value = typeof submodules === "string" ? submodules : "true";
    yaml += `\n        with:\n          submodules: ${value}`;
  }
  yaml += "\n" + indent(buildSteps, 6);
  const modeValue = modeList.join(",");
  yaml += `
      - name: Run the benchmarks
        uses: CodSpeedHQ/action@v4
        with:
          mode: ${modeValue}`;
  if (benchmarkCommand.length > 0) {
    const indentedBenchCommand = benchmarkCommand.length > 1 ? benchmarkCommand[0] + "\n" + indent(benchmarkCommand.slice(1), 12) : benchmarkCommand;
    const runLine = indent(["run: "], 10) + indentedBenchCommand;
    yaml += `\n${runLine}`;
  }
  const envEntries = Object.entries(env);
  if (envEntries.length > 0) {
    const envLines = ["env:", ...envEntries.map(([k, v]) => `  ${k}: ${v}`)];
    yaml += "\n" + indent(envLines, 8);
  }
  return <CodeBlock language="yaml" highlight={JSON.stringify(highlight)} {...minimal || ({
    filename: ".github/workflows/codspeed.yml",
    icon: "github"
  })}>
      {yaml}
    </CodeBlock>;
};

Running benchmarks in CI environments presents unique challenges due to the
inherent noise and variability of shared cloud infrastructure. Standard
GitHub-hosted runners can exhibit significant performance variance.

<Tip>
  Read our detailed post on [how CI noise affects benchmark
  consistency](https://codspeed.io/blog/benchmarks-in-ci-without-noise).
</Tip>

[CodSpeed instruments](/instruments) are designed to mitigate these challenges
and gather accurate performance data even in noisy environments. The easiest way
to get started running benchmarks in GitHub Actions is to use the
[CodSpeed GitHub Action](https://github.com/CodSpeedHQ/action).

## 1. Create the benchmarks workflow

Create a new workflow to run the benchmarks for your repository.

You can do this by creating the `codspeed.yml` file in the `.github/workflows`
directory with the following content:

<CIWorkflow mode="simulation" highlight={[20, 21, 22, 23, 24, 25, 30]} />

The most important step of this workflow is the usage of
[`CodSpeedHQ/action`](https://github.com/CodSpeedHQ/action). This action will
configure the CodSpeed environment and upload the benchmarks results.

<Note>
  Make sure to include `pull_request` in the `on` section of the workflow. This is
  required to have reports on pull requests correctly working.

  Learn more about
  [baseline report selection](/features/understanding-the-metrics#baseline-report-selection).
</Note>

<Tip>
  **Public repositories**

  CodSpeed allows tokenless uploads for public repositories, allowing runs to be
  triggered from public forks directly.

  To enable this, you can simply omit the `permissions` section.

  Learn more about
  [authentication methods](/integrations/ci/github-actions/configuration#authentication).
</Tip>

### Sample configurations

* [Python (with `pytest-codspeed`)](https://github.com/CodSpeedHQ/action/blob/main/examples/python-pytest-codspeed.yml)
* [Rust (with `cargo-codspeed`)](https://github.com/CodSpeedHQ/action/blob/main/examples/rust-cargo-codspeed.yml)
* [Node.js (with `codspeed-node` and TypeScript)](https://github.com/CodSpeedHQ/action/blob/main/examples/nodejs-typescript-codspeed.yml)

## 2. Check the results

Once the workflow is created, your pull requests will receive a performance
report comment and will also receive some additional checks:

<img src="https://mintcdn.com/codspeed/jKaxX6yy-Kzw1C-0/assets/pr-comment-new-installation.png?fit=max&auto=format&n=jKaxX6yy-Kzw1C-0&q=85&s=4405db6390fe6f80b4f13d5baa2598d1" className="rounded-xl w-full max-w-lg mx-auto" alt="Pull Request Result" width="1744" height="820" data-path="assets/pr-comment-new-installation.png" />

<img src="https://mintcdn.com/codspeed/jKaxX6yy-Kzw1C-0/assets/pr-status-check-success.png?fit=max&auto=format&n=jKaxX6yy-Kzw1C-0&q=85&s=a74b568e364c0b068623bd31ee869361" className="rounded-xl w-full max-w-md mx-auto" alt="Pull Request Result" width="1408" height="690" data-path="assets/pr-status-check-success.png" />

## 3. Next Steps

Now that everything is up and running (and hopefully green 🎉), you can start
enhancing your workflow to get the most out of CodSpeed.

<Card title="Configure GitHub Actions for CodSpeed" href="/integrations/ci/github-actions/configuration" icon="cog">
  Learn how to configure authentication methods and advanced options for GitHub
  Actions
</Card>

<Columns cols={2}>
  <Card title="Explore the Performance Metrics" href="/features/understanding-the-metrics/" icon="chart-line">
    Understand the performance metrics generated by CodSpeed
  </Card>

  <Card title="Enforce Performance Checks" href="/features/performance-checks/" icon="shield-check">
    Make sure you or team members never merge unexpected performance regressions
  </Card>

  <Card title="Explore Profiling" href="/features/profiling" icon="bars-sort">
    Get detailed flame graphs and performance traces for your benchmarks
  </Card>

  <Card title="Shard the execution of your benchmarks" href="/features/sharded-benchmarks/" icon="layer-group">
    Run your benchmarks in parallel to speed up your CI
  </Card>
</Columns>
