Measure code speed in .net in milliseconds

后端 未结 4 474
灰色年华
灰色年华 2021-02-03 11:09

I want to get the maximum count I have to execute a loop for it to take x milliseconds to finish.

For eg.

int GetIterationsForExecutionTime(int ms)
{
            


        
4条回答
  •  不知归路
    2021-02-03 12:08

    Good points from Eric Lippert. I'd been benchmarking and unit testing for a while and I'd advise you should discard every first-pass on you code cause JIT compilation. So in a benchmarking code which use loop and Stopwatch remember to put this at the end of the loop:

                    // JIT optimization.
                    if (i == 0)
                    {
                        // Discard every result you've collected.
                        // And restart the timer.
                        stopwatch.Restart();
                    }
    

提交回复
热议问题