本文介绍了说明有关与.NET秒表高分辨率性能计数器和它的存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在静态秒表的构造函数,我们可以看到下面的代码,这basicly检查高分辨率性能计数器是否存在。

 静态秒表()
{
如果(!SafeNativeMethods.QueryPerformanceFrequency(输出频率))
{
IsHighResolution = FALSE ;
频率= 0x989680L;
tickFrequency = 1.0;
}
,否则
{
IsHighResolution = TRUE;
tickFrequency = 10000000.0;
tickFrequency / =(双)频率;
}
}

在MSDN它说,关于 QueryPerformanceFrequency的



It's pretty unclear, however, when exactly does it exist? I suspect it usually exists on current machines, but when exactly doesn't it?

It's interesting because when it doesn't exist, Stopwatch becomes a mere wrapper around the DateTime.UtcNow property.

解决方案

There is a difference between a timer and a stopwatch, and confusing the two leads to erroneous assumptions. Unfortunately, the term timer is used to mean multiple things all too often.

Any machine that runs Windows 2000 or later likely has a high frequency timer. I have never run across a computer that runs Windows 2000 later that does not have such a thing.

Now, that's the high frequency timer. There are also timers: Windows or .NET components. These timers are not used for keeping time or for measuring time, but rather for performing actions at periodic intervals. The Windows timer objects are capable of 1 ms resolution, and are very reliable when the computer is not involved in CPU intensive operations. The .NET timer objects are limited to approximately 15 ms resolution. You can get around that by using P/Invoke to interact directly with the Windows objects, but it's not often necessary.

The .NET Stopwatch class is based on the high frequency timer. In general, Start queries the performance counter and stores the value. When you Stop, it queries the performance counter again. The elapsed time is a simple subtraction of those two values. You can get better than microsecond resolution from the Stopwatch.

And in fact, you can create use a Stopwatch with a busy-waiting loop that gives you sub-millisecond resolution. I doubt that you could get sub-microsecond resolution with it.

The important thing to understand is that, although timers aren't reliable beyond 1 millisecond, the stopwatch, which measures elapsed time, is much more precise. You can probably trust microsecond-level elapsed time measurements from Stopwatch. Beyond that, I wouldn't count on it.

这篇关于说明有关与.NET秒表高分辨率性能计数器和它的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:51