Usage modes
NBenchmark has four usage modes. Pick the one that matches your situation.
Single mode - Benchmark
A single static call. No classes, no attributes, no configuration required. Good for a quick measurement anywhere in your code.
var result = Benchmark.Run(() => MyMethod());
result.Print();Suite mode - BenchmarkSuite
A fluent builder for comparing multiple implementations. Produces a comparison table with ratios, confidence intervals, and significance testing.
await new BenchmarkSuite("sorting")
.Add("bubble", BubbleSort)
.Add("linq", LinqSort)
.WithBaseline("bubble")
.WithReporter(new ConsoleReporter())
.RunAsync();Harness mode - BenchmarkHarness
Attribute-based discovery driven by a command-line interface. Designed for dedicated benchmark projects.
await BenchmarkHarness.Create(args)
.AddFromAssembly<MyBenchmarks>()
.WithReporter(new ConsoleReporter())
.RunAsync();
public class MyBenchmarks
{
[Benchmark(Baseline = true)]
public int Baseline() => 1;
[Benchmark]
public int Compute() => SomeExpensiveWork();
}Global Tool - dotnet benchmark
A dotnet global tool that wraps BenchmarkHarness into a single command. Install once, then run benchmarks against any assembly without creating a project.
dotnet tool install -g NBenchmark.Tool
dotnet benchmark --project ./MyBenchmarks --filter "*Sort*"When to switch modes
The modes are designed as an evolutionary path. Start simple, upgrade when your needs grow:
Start with Single mode for a one-off measurement - a single
Benchmark.Runcall gives you a statistically rigorous result in three lines of code.Move to Suite mode when you find yourself writing two
Benchmark.Runcalls to compare an old implementation against a new one. Suite mode handles the comparison automatically - ratios, confidence intervals, and significance testing against a baseline - so you don't have to mentally diff two separate outputs.Move to Harness mode when your suite requires complex setup: mocked databases, loggers,
HttpClient, or any dependency-injected service. Harness mode discovers benchmarks by attribute, parses CLI flags, and supports constructor injection via the optionalNBenchmark.DependencyInjectionpackage.Use the Global Tool when you already have a project with
[Benchmark]methods and want to run them from the CLI without adding aProgram.cs, NuGet references, or any project setup. The tool wraps Harness mode into a singledotnet benchmarkcommand.
Because all four modes produce the same BenchmarkResult type, upgrading from one mode to the next is seamless - your reporters, file output, and analysis code work unchanged.
Next steps
Once you've picked a mode, the Features section covers advanced cross-cutting capabilities: parameterized benchmarks, categories, isolated runs, multi-runtime comparison, multiple launches, and dependency injection.
