dotnet / BenchmarkDotNet

Powerful .NET library for benchmarking
https://benchmarkdotnet.org
MIT License
10.24k stars 952 forks source link

How to set the loop count for benchmarking #2578

Closed ooosan closed 1 month ago

ooosan commented 1 month ago

This is my code:

private const int Iterations = 100000;
private const int ArraySize = 600000;
private int fParaIntSub = 0;
public int[] fIntA2 = new int[ArraySize];
public int[] fIntB2 = new int[ArraySize];

[GlobalSetup]
public void GlobalSetup()
{
    fParaIntSub = 0;
    Random random = new Random();
    for (int i = 0; i < ArraySize; i++)
    {
        fIntA2[i] = random.Next();
        fIntB2[i] = random.Next();
        if (fIntB2[i] == 0)
        {
            fIntB2[i] = fIntB2[i] + 1;
        }
    }

}

[Benchmark]
[IterationCount(1000)]
public int IntSubtraction()
{
    Console.WriteLine("sub:" + fParaIntSub);
    int temp = fIntA2[fParaIntSub] - fIntB2[fParaIntSub];
    ++fParaIntSub;
    return temp;
}

the final printed result shows that it exceeds five hundred thousand. If I don't write "Console.WriteLine("sub:" + fParaIntSub);", the program won't be able to run. What could be the reason for this?

timcassell commented 1 month ago

You can use [InvocationCount(...)] to control how many times the method will be invoked per iteration.

I tried your code with and without the Console.Writeline, and it worked for me.

adamsitnik commented 1 month ago

The provided benchmark is also wrong, please consider reading https://github.com/dotnet/performance/blob/main/docs/microbenchmark-design-guidelines.md