我尝试捕获函数的确切执行时间
Stopwatch regularSW = new Stopwatch();
for (int i = 0; i < 10; i++) {
regularSW.Start();
//function();
regularSW.Stop();
Console.WriteLine("Measured time: " + regularSW.Elapsed);
}
我也试过DateTime
和Process.GetCurrentProcess().TotalProcessorTime
但每次我得到不同的价值。
我如何获得相同的价值?
答案 0 :(得分:5)
使用StopWatch
,您已经使用了最准确的方法。但是你没有在循环中重新启动它。它总是从它结束的值开始。您必须创建新的StopWatch
或致电StopWatch.Restart
而不是Start
:
Stopwatch regularSW = new Stopwatch();
for (int i = 0; i < 10; i++) {
regularSW.Restart();
//function();
regularSW.Stop();
Console.WriteLine("Measured time: " + regularSW.Elapsed);
}
这就是不同价值观的原因。如果你现在仍然得到不同的值,那么原因是方法function
确实具有不同的执行时间,这不是那么不可能(例如,如果它是数据库查询)。
由于这个问题似乎主要是理论上的(关于你的评论),如果你想在.NET中测量时间,请考虑以下事项:
最后两点是从this answer of Eric Lippert复制的(值得一读)。