Running BenchmarkDotNet within XUnit

I have created a wrapper test fixture that runs the benchmarks, collects the output and prints the summary at the end:

public class Benchmarks
{
    private readonly ITestOutputHelper output;

    public Benchmarks(ITestOutputHelper output)
    {
        this.output = output;
    }

    [Fact]
    public void Run_Benchmarks()
    {
        var logger = new AccumulationLogger();

        var config = ManualConfig.Create(DefaultConfig.Instance)
            .AddLogger(logger)
            .WithOptions(ConfigOptions.DisableOptimizationsValidator);

        BenchmarkRunner.Run<FooBenchmarks>(config);

        // write benchmark summary
        output.WriteLine(logger.GetLog());
    }
}

[MemoryDiagnoser]
public class FooBenchmarks
{
    [GlobalSetup]
    public void Setup()
    {
        ModuleInitializer.Initialize();
        ...
    }

    [Benchmark]
    public async Task ProcessRequest_Benchmark()
    {
        ...
    }
}

Leave a Comment