C++ USES Windows functions to implement the timing example

  • 2020-04-02 02:23:10
  • OfStack


//Time(), clock(), timeGetTime(), GetTickCount(), QueryPerformanceCounter() can be used on Windows to time a piece of program code
#include <stdio.h>
#include <windows.h>
#include <time.h>                   //time_t time()  clock_t clock()    
#include <Mmsystem.h>               //timeGetTime()    
#pragma comment(lib, "Winmm.lib")   //timeGetTime()    
//How to use: replace the Sleep() function with one that requires the test run time.
int main()
{   //Time is measured in seconds using time()
    time_t timeBegin, timeEnd;
    timeBegin = time(NULL);
    Sleep(1000);
    timeEnd = time(NULL);
    printf("%dn", timeEnd - timeBegin);

    //Time by clock(), in milliseconds
    clock_t  clockBegin, clockEnd;
    clockBegin = clock();
    Sleep(800);
    clockEnd = clock();
    printf("%dn", clockEnd - clockBegin);

    //Time with timeGetTime(), in milliseconds
    DWORD  dwBegin, dwEnd;
    dwBegin = timeGetTime();
    Sleep(800);
    dwEnd = timeGetTime();
    printf("%dn", dwEnd - dwBegin);

    //Time with GetTickCount() in milliseconds
    DWORD  dwGTCBegin, dwGTCEnd;
    dwGTCBegin = GetTickCount();
    Sleep(800);
    dwGTCEnd = GetTickCount();
    printf("%dn", dwGTCEnd - dwGTCBegin);

    //The QueryPerformanceCounter() is used to time the performance in microseconds
    LARGE_INTEGER  large_interger;
    double dff;
    __int64  c1, c2;
    QueryPerformanceFrequency(&large_interger);
    dff = large_interger.QuadPart;
    QueryPerformanceCounter(&large_interger);
    c1 = large_interger.QuadPart;
    Sleep(800);
    QueryPerformanceCounter(&large_interger);
    c2 = large_interger.QuadPart;
    printf(" High precision timer frequency %lfn", dff);
    printf(" First timer value %I64dn Second timer value %I64dn The timer is poor %I64dn", c1, c2, c2 - c1);
    printf(" timing %lf ms nn", (c2 - c1) * 1000 / dff);
    return 0;
}



Related articles: