How to do multi-step benchmarks? #2484
-
Hi there, I'd like to create multi-step benchmarks to measure each step of a longer routine. Here's what I mean:
I would like to benchmark this sequence and get the metrics (CPU and allocations) for each step (1, 2, 3, 4). Is there a way to do something like this using BenchmarkDotNet? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
It's not simple (or portable), but you can do it with public class Benchmark
{
// Adjust this value until BenchmarkDotNet is happy with benchmark time > 100ms
const int invokeCount = 100_000;
private MyObject[] _objects = new MyObject[invokeCount];
[IterationSetup(Target = nameof(MemberA))]
public void IterationSetup()
{
for (int i = 0; i < invokeCount; ++i)
{
_objects[i] = new MyObject();
}
}
[IterationCleanup(Target = nameof(MemberA))]
public void IterationSetup()
{
for (int i = 0; i < invokeCount; ++i)
{
_objects[i].Dispose();
}
}
[Benchmark(OperationsPerInvoke = invokeCount)]
public void MemberA()
{
for (int i = 0; i < invokeCount; ++i)
{
_objects[i].MemberA();
}
}
} |
Beta Was this translation helpful? Give feedback.
My point was you have to create a separate benchmark for each step, each with its own setup and cleanup.