Measure code speed in .net in milliseconds

后端 未结 4 475
灰色年华
灰色年华 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 11:41

    You could also use the Stopwatch class:

    int GetIterationsForExecutionTime(int ms)
    {
        int count = 0;
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();        
        do
        {
            // some code here
            count++;
        } while (stopwatch.ElapsedMilliseconds < ms);
    
        stopwatch.Stop();
        return count;
    }
    

提交回复
热议问题