If the current system supports high-resolution counters, we can use QueryPerformanceCounter and QueryPerformanceFrequency for high-resolution timing.
QueryPerformanceFrequency ()
Type: Win32API
Prototype: BOOL QueryPerformanceFrequency (LARGE_INTEGER * lpFrequency );
Purpose: return the hardware-supported high-precision counter frequency.
Returned value: non-zero, hardware supports high-precision counters, zero, hardware does not support, read failed
FunctionQueryPerformanceCounterUsed to obtain the value of a high-precision timer (if such a timer exists)
Prototype: BOOL QueryPerformanceCounter (LARGE_INTEGER * ipPerformanceCount); // The parameter points to the counter value.
Parameter: LARGE_INTEGER * ipProformanceCount
A pointer variable is used to pass a value to the function, that is, to the current counter value. If the installed hardware does not support a high-precision timer, this parameter returns 0,
Return Value:
If the installed hardware supports a high-precision timer, the function returns a non-zero value.
If the installed hardware does not support high-precision timers, the function returns 0.
Implementation of a time class
View Code
// -------------------------------- Header file --------------------- # pragma once # include <Windows. h> class CTime {private: CTime (void );~ CTime (void); public: static UINT64 GetMilliS (); // millisecond static UINT64 GetMicroS (); // microsecond static UINT64 GetNanoS (); // nanosecond private: static UINT64 m_frequency; static CTime m_self;}; // ---------------------------------- CTime. cpp ------------------------------ # include "ctime. h "# include <assert. h> UINT64 CTime: m_frequency = 0; CTime: m_self; CTime: CTime (void) {LARGE_INTEGER fc; if (! QueryPerformanceFrequency (& fc) {assert (FALSE) ;}m_frequency = fc. QuadPart; // timer frequency} CTime ::~ CTime (void) {} UINT64 CTime: GetMilliS () {assert (m_frequency> 1000); LARGE_INTEGER fc; if (! QueryPerformanceCounter (& fc) {assert (FALSE);} UINT64 c = fc. quadPart; UINT64 s = (c)/(m_frequency/1000); return s;} UINT64 CTime: GetMicroS () {assert (m_frequency> 1000*1000); LARGE_INTEGER fc; if (! QueryPerformanceCounter (& fc) {assert (FALSE);} UINT64 c = fc. quadPart; UINT64 s = (c)/(m_frequency/1000/1000); return s;} UINT64 CTime: GetNanoS () {assert (m_frequency> 1000x1000*1000 ); LARGE_INTEGER fc; if (! QueryPerformanceCounter (& fc) {assert (FALSE);} UINT64 c = fc. QuadPart; UINT64 s = (c)/(m_frequency/1000/1000/1000); return s ;}
If the system does not support high-precision timers, you can use GetTickCount () with a precision of milliseconds. You can also use clock () with a precision of milliseconds.