Sample: IntroSetupCleanupGlobal
A method which is marked by the [GlobalSetup]
attribute will be executed only once per a benchmarked method
after initialization of benchmark parameters and before all the benchmark method invocations.
A method which is marked by the [GlobalCleanup]
attribute will be executed only once per a benchmarked method
after all the benchmark method invocations.
If you are using some unmanaged resources (e.g., which were created in the GlobalSetup
method),
they can be disposed in the GlobalCleanup
method.
Source code
using BenchmarkDotNet.Attributes;
namespace BenchmarkDotNet.Samples
{
public class IntroSetupCleanupGlobal
{
[Params(10, 100, 1000)]
public int N;
private int[] data;
[GlobalSetup]
public void GlobalSetup()
{
data = new int[N]; // executed once per each N value
}
[Benchmark]
public int Logic()
{
int res = 0;
for (int i = 0; i < N; i++)
res += data[i];
return res;
}
[GlobalCleanup]
public void GlobalCleanup()
{
// Disposing logic
}
}
}
Links
- Setup And Cleanup
- The permanent link to this sample: BenchmarkDotNet.Samples.IntroSetupCleanupGlobal