Accurately calculate time through CPU oscillation

Two functions are used here, QueryPerformanceFrequency and QueryPerformanceCount, which are the frequency and the number of acquisitions, and the number/frequency = time (time is seconds)

 

BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency); High-precision frequency

QueryPerformanceCounter: Retrieve the current value of the high-resolution performance counter

The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter, if one exists.

BOOL QueryPerformanceCounter(

LARGE_INTEGER *lpPerformanceCount // pointer to counter value

);

Parameters

lpPerformanceCount

Pointer to a variable that the function sets, in counts, to the current performance-counter value. If the installed hardware does not support a high-resolution performance counter, this parameter can be to zero.

Return Values

If the installed hardware supports a high-resolution performance counter, the return value is nonzero.

If the installed hardware does not support a high-resolution performance counter, the return value is zero.

Calculate nanoseconds

    __int64  c1, c2;
    LARGE_INTEGER  large_interger;
    double dff;
    QueryPerformanceFrequency(&large_interger);
    dff = large_interger.QuadPart;
 
    QueryPerformanceCounter(&large_interger);
    c1 = large_interger.QuadPart;
 

    //Time-consuming code. . . .

            
    QueryPerformanceCounter(&large_interger);
    c2 = large_interger.QuadPart;

    printf("sync time:%lf(us)\n",(c2 - c1)*1000000/dff);

Guess you like

Origin blog.csdn.net/wyyy2088511/article/details/108749004