How to do multi-step benchmarks? #2484
Answered by timcassell
jeanplevesque asked this question in Q&A
-
| 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.
Answered by timcassell Feb 2, 2024
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.
2 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
My point was you have to create a separate benchmark for each step, each with its own setup and cleanup.