Post

Run BenchmarkDotNet in xUnit

If you ever need to run BenchmarkDotNet as part of the unit test (because sometimes it’s easier to just write unit tests instead of a dedicated app), you can use this wrapper around benchmark runner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[Trait("Category", "Unit")]
public class PerformanceTests
{
    private readonly ITestOutputHelper _output;

    public PerformanceTests(ITestOutputHelper output)
    {
        _output = output;
    }

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

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

        BenchmarkRunner.Run<HeavyBenchmarks>(config);

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

[MemoryDiagnoser]
public class HeavyBenchmarks
{
    [Benchmark]
    public void ProcessRequest()
    {
        var sut = new HeavyClass();
        sut.HeavyMethod();
    }
}

Happy unit benchmarking!

[eof]

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.