获得进程/线程已经被分配的所有cpu时间片的总和

时间:2022-09-09 21:19:20

主要就是GetProcessTimes和GetThreadTimes这两个函数,它们获得的时间都是FILETIME,下面的程序包含了获得两个FILETIME的差(ms)的办法。

如果要显示FILETIME,可以用FileTimeToSystemTime这个函数(http://msdn.microsoft.com/en-us/library/windows/desktop/ms724280(v=vs.85).aspx

 

补充,这里有一个跨平台的版本:

http://nadeausoftware.com/articles/2012/03/c_c_tip_how_measure_cpu_time_benchmarking

 1 #include "stdafx.h"
 2 #include <windows.h>
 3 #include <iostream>
 4 
 5 int GetMSBetweenFileTime(PFILETIME ft1, PFILETIME ft2)
 6 {
 7     ULARGE_INTEGER ul1;
 8     ULARGE_INTEGER ul2;
 9 
10     ul1.LowPart = ft1->dwLowDateTime;
11     ul1.HighPart = ft1->dwHighDateTime;
12 
13     ul2.LowPart = ft2->dwLowDateTime;
14     ul2.HighPart = ft2->dwHighDateTime;
15 
16     ULARGE_INTEGER uliRetValue;
17     uliRetValue.QuadPart = ul2.QuadPart - ul1.QuadPart;
18     uliRetValue.QuadPart /= 10;
19     uliRetValue.QuadPart /= 1000;
20 
21     return int(uliRetValue.QuadPart);
22 }
23 
24 int _tmain(int argc, _TCHAR* argv[])
25 {
26     FILETIME cpuTime;
27     FILETIME sysTime;
28     FILETIME createTime;
29     FILETIME exitTime;
30     
31     BOOL c1 = GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &sysTime, &cpuTime);    
32     
33     for(int i = 0; i < 1000; i++)
34         std::cout << i << std::endl;
35 
36     Sleep(3000);
37     FILETIME cpuTime2;
38     FILETIME sysTime2;
39     FILETIME createTime2;
40     FILETIME exitTime2;
41 
42     BOOL c2 = GetProcessTimes(GetCurrentProcess(), &createTime2, &exitTime2, &sysTime2, &cpuTime2);
43 
44     std::cout << "sysTime:" << GetMSBetweenFileTime(&sysTime, &sysTime2) << std::endl;
45     std::cout << "cpuTime:" << GetMSBetweenFileTime(&cpuTime, &cpuTime2) << std::endl;
46     std::cout << "Done";
47 }