且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获得最准确的时间戳

更新时间:2023-02-26 17:21:32

我在QueryPerformanceCounter API函数周围使用了一个小包装器类。以下是它的简化版本:
I use a little wrapper class around the QueryPerformanceCounter API function. Here is a stripped down version of it:
class CElapsed
{
public :
   CElapsed()   // constructor
   {
        // get the frequency of the performance counter and its period in seconds

        LARGE_INTEGER li = { 0 };
        m_Period = QueryPerformanceFrequency( &li ) ? 1.0 / (double)li.QuadPart : 0;
   }

   // get the current performance counter value, convert it
   // to seconds, and return the difference from begin in seconds

   double TimeSince( double begin=0 )
   {
       LARGE_INTEGER endtime;
       QueryPerformanceCounter( &endtime );
       return ( endtime.QuadPart * m_Period ) - begin;
   }

   // returns true if the counter is available

   bool IsAvailable()     { return m_Period != 0; }

   // return the counter frequency

   double GetFrequency()  { return 1.0 / m_Period; }

protected :
   double  m_Period;
};

这是一个如何使用它的例子:

Here is an example of how to use it :

CElapsed et;
double start = et.TimeSince( 0 );

// code to time goes here

double elapsed = et.TimeSince( start );
_tprintf( _T( "elapsed time was %.3f seconds\n" ), elapsed );

我建议您阅读QueryPerformanceCounter以查看其属性。计数器频率取决于机器,但几乎总是在兆赫兹范围内,所以它的分辨率在几微秒内,但确实有一些开销。我从来不需要分辨率低于毫秒的时间,所以这对我的目的来说是足够的。



这种计时器类有很多变种。我喜欢这个实现,因为它不保留起始值。这允许一个计时器对象同时用于许多事情。事实上,如果你想这样做,一个计时器对象可以用于整个应用程序。构造也是最小的,因此可以快速,轻松地创建实例,而且开销最小。

I recommend reading up on QueryPerformanceCounter to see what its properties are. The counter frequency is machine-dependent but is nearly always in the megahertz range so its resolution is in the microseconds but it does have some overhead. I have never needed timing with a resolution of under a millisecond so this is adequate for my purposes.

There are many variations of this kind of timer class. I like this implementation because it does NOT retain the starting value. This allows one timer object to be used for many things simultaneously. In fact, one timer object can be used for an entire application if you want to do that. Construction is also minimal so instances can be created quickly and easily with a minimum of overhead.


请参见此处: GetTickCount函数| Microsoft Docs [ ^ ]和这里:关于计时器 - Windows应用程序| Microsoft Docs [ ^ ]



分辨率不固定:它因系统而异,因此在运行相同软件的两台不同PC上获得的分辨率可能不同。
See here: GetTickCount function | Microsoft Docs[^] and here: About Timers - Windows applications | Microsoft Docs[^]

Resolution is not fixed: it varies by system, so what you get on two different PCs running the same software may be different.