秒表与使用 System.DateTime。现在开始计时事件

我想跟踪我的代码的性能,所以我使用 System.DateTime.Now存储开始和结束时间。我将两者之间的差值作为代码执行的时间。

我注意到这种差别似乎并不准确。所以我尝试使用 Stopwatch对象。事实证明,这种说法要准确得多。

有人能告诉我为什么 Stopwatch会比使用 System.DateTime.Now计算开始和结束时间的差更准确吗?

顺便说一下,我说的不是0.1% ,而是15% 到20% 的差别。

70848 次浏览

As per MSDN:

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

It uses a higher resolution / precision than DateTime.Now.

You can also check out these related links:

Environment.TickCount vs DateTime.Now

Is DateTime.Now the best way to measure a function's performance?

DateTime is good enough for precision to the second probably but anything beyond that I would recommend StopWatch.

this timing function performance link discusses your exact problem, specifically this paragraph:

The problem is that according to MSDN the resolution of the DateTime.Now function is 10+ milliseconds, and we need to call it twice! So that would introduce a 20+ ms swing in your runtime measurement. As our function calls are often likely to be a lot quicker to return than this 20ms window this isn’t good enough.

EDIT: It kind of sounds like the second DateTime.Now is being called at a different time than when the stopwatch method concludes.

It's better to use the Stopwatch class because it's much more accurate than subtracting DateTime values:

Stopwatch s = Stopwatch.StartNew();
// Tested code here
s.Stop();
Console.WriteLine("Elapsed Time: {0} ms", s.ElapsedMilliseconds);

Unfortunately, this simple piece of code won't be enough to get accurate measurements most of the times because there’s a lot of activity going on under the hood of the OS, which can steal some CPU time and slow down the execution of your code. That’s why it is best to execute the tests multiple times and then remove the lowest and the highest times. For that puprose it is a good solution to have a method that executes the tested code multiple times, removes the lowest and the greatest times and calculates the average time. I have published a sample testing method in my blog.