在编写单元测试时,我们可以通过向集合中添加元素来添加更多的测试用例,例如在 NUnit 中使用 TestCaseSource
。
在 BenchmarkDotNet 中是否有类似的方法,可以从一个集合创建一组基准测试?
这将节省很多模板代码,特别是在对基准测试方法进行额外测试或对多个输入组合进行基准测试时。
最简示例代码:
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public interface IAlgorithm
{
public void DoWork();
}
public class AlgorithmA: IAlgorithm
{
public void DoWork() { } // something slow
}
public class AlgorithmB : IAlgorithm
{
public void DoWork() { } // something slow
}
public class MyBenchmarks
{
AlgorithmA classA = new AlgorithmA();
AlgorithmB classB = new AlgorithmB();
[Benchmark]
public void A() => classA.DoWork();
[Benchmark]
public void B() => classB.DoWork();
}
public class WhatIWouldLike
{
IAlgorithm[] classes = new IAlgorithm[] { new AlgorithmA(), new AlgorithmB() };
// ...automatically create a benchmark for DoWork() on element of the array
}
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<MyBenchmarks>();
}
}