Writing benchmarks with vitest-bench
Installation
First install the plugin
@codspeed/vitest-plugin
and vitest
(if not already installed):
The CodSpeed plugin is only compatible with
vitest
v1.2.2 and above.
Usage
Creating benchmarks
Let’s create a fibonacci function and benchmark it with vitest and the CodSpeed plugin:
Here, a few things are happening:
- We create a simple recursive fibonacci function.
- We create a new
vitest
suite"fibo"
with two benchmarks, benching ourfibonacci
function for 10 and 15.
Create or update the vitest.config.ts
file to use the CodSpeed runner:
Testing the benchmarks locally
Now, we can run our benchmarks locally to make sure everything is working as expected:
This will run the benchmarks and output the results in the terminal (for
example, with pnpm
):
Troubleshooting errors
If you encounter an error like
Failed to resolve "@codspeed/vitest-plugin" from "vitest.config.ts"
, you might
need to rename the vitest.config.ts
file to vitest.config.mts
.
You can find more information in the Vite documentation on importing ESM package.
And… Congrats🎉, CodSpeed is installed in your benchmarking suite! Locally,
CodSpeed will fall back to vitest
since the instrumentation is only available
in the CI environment for now.
You can now run those benchmarks in your CI to get consistent performance measurements.
Running the benchmarks in your CI
To generate performance reports, you need to run the benchmarks in your CI. This allows CodSpeed to detect the CI environment and properly configure the instrumented environment.
If you want more details on how to configure the CodSpeed action, you can check out the Continuous Reporting section.
Here is an example of a GitHub Actions workflow that runs the benchmarks and
reports the results to CodSpeed on every push to the main
branch and every
pull request:
Recipes
Running benchmarks in parallel CI jobs
To parallelize your benchmarks, you can use the
shard
options from vitest.
For example with pnpm
on Github Actions:
Same benchmark with different variations
For now, you cannot run the same benchmarks several times within the same run. If the same benchmark is run multiple times, you will receive the following comment on your pull request:
Learn more about benchmark sharding and how to integrate with your CI provider.