Computing CPU time in C++ on Windows

后端 未结 5 907
無奈伤痛
無奈伤痛 2021-02-03 14:50

Is there any way in C++ to calculate how long does it take to run a given program or routine in CPU time?

I work with Visual Studio 2008 running on Wind

5条回答
  •  旧巷少年郎
    2021-02-03 15:13

    This Code is Process Cpu Usage

    ULONGLONG LastCycleTime = NULL;
    LARGE_INTEGER LastPCounter;
    LastPCounter.QuadPart = 0; // LARGE_INTEGER Init
    
                               // cpu get core number
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);
    int numProcessors = sysInfo.dwNumberOfProcessors;
    
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, Process::pid);
    
    if (hProcess == NULL)
        nResult = 0;
    
    int count = 0;
    while (true)
    {
        ULONG64 CycleTime;
        LARGE_INTEGER qpcLastInt;
    
        if (!QueryProcessCycleTime(hProcess, &CycleTime))
            nResult = 0;
    
        ULONG64 cycle = CycleTime - LastCycleTime;
    
        if (!QueryPerformanceCounter(&qpcLastInt))
            nResult = 0;
    
        double Usage = cycle / ((double)(qpcLastInt.QuadPart - LastPCounter.QuadPart));
    
        // Scaling
        Usage *= 1.0 / numProcessors;
        Usage *= 0.1;
    
        LastPCounter = qpcLastInt;
        LastCycleTime = CycleTime;
    
        if (count > 3)
        {
            printf("%.1f", Usage);
            break;
        }
    
        Sleep(1); // QueryPerformanceCounter Function Resolution is 1 microsecond
    
        count++;
    }
    
    CloseHandle(hProcess);
    

提交回复
热议问题