1. 定义
本文CPU利用率定义为;用户进程时间 / (用户进程时间 + 内核时间)。
2.相关库函数介绍
(1)GetSystemTimes
函数声明为:
- BOOL WINAPI GetSystemTimes(
-
__out_opt LPFILETIME lpIdleTime,
-
__out_opt LPFILETIME lpKernelTime,
-
__out_opt LPFILETIME lpUserTime
-
);
本函数返回系统时序信息,在多核处理器环境下,返回值为所有核心的求和。
本函数返回3个时间信息,分别是空闲时间、内核时间、用户进程时间。windows系统处于空闲时会运行SystemIdle进程,该进程运行在内核态,因此空闲时间位于内核时间内。
3.相关数据结构介绍
FILETIME
本数据结构定位如下:
- typedef struct _FILETIME {
-
DWORD dwLowDateTime;
-
DWORD dwHighDateTime;
-
} FILETIME, *PFILETIME;
FILETIME数据结构为一个64位数据,它表示从1601年1月1日起,距离现在100纳米时间单位的数量。
4.简单样例
- #include <windows.h>
-
#include <iostream>
-
#include <string>
-
-
using std::cout;
-
using std::endl;
-
using std::cin;
-
-
int main(){
-
-
std::string input;
-
DWORD interval = 1000*1000*10; // sampling interval is 1000ms
-
typedef unsigned long long uint64;
-
uint64 valKernel;
-
uint64 valUser;
-
uint64 valAll;
-
-
SYSTEM_INFO sysInfo;
-
GetSystemInfo(&sysInfo);
-
-
-
-
DWORD NumCPU = sysInfo.dwNumberOfProcessors;
-
-
cout << "CPU Number is :" << NumCPU << endl;
-
-
FILETIME kernelTime;
-
FILETIME userTime;
-
FILETIME idleTime;
-
-
cout << "sizeof(uint64) = " << sizeof(uint64) << endl;
-
-
BOOL ret = GetSystemTimes( &idleTime, &kernelTime, &userTime);
-
if( !ret ){
-
cout << "Fail to call GetSystemTimes." << endl;
-
return 1;
-
}
-
-
uint64 start = userTime.dwHighDateTime;
-
start = start << 32;
-
start += userTime.dwLowDateTime;
-
-
uint64 startKernel = kernelTime.dwHighDateTime;
-
startKernel <<= 32;
-
startKernel += kernelTime.dwLowDateTime;
-
-
while(1){
-
-
::Sleep(1000);
-
BOOL ret = GetSystemTimes( &idleTime, &kernelTime, &userTime);
-
if( !ret ){
-
cout << "Fail to call GetSystemTimes." << endl;
-
continue;
-
}
-
valUser = userTime.dwHighDateTime;
-
valUser <<= 32;
-
valUser += userTime.dwLowDateTime;
-
-
valKernel = kernelTime.dwHighDateTime;
-
valKernel <<= 32;
-
valKernel += kernelTime.dwLowDateTime;
-
-
valAll = (valUser-start) + valKernel-startKernel;
-
-
WORD used = 100*(valUser-start)/valAll;
-
-
cout << "CPU per : " << used << endl;
-
start = valUser;
-
startKernel = valKernel;
-
-
}
-
-
return 0;
-
}
阅读(2717) | 评论(0) | 转发(0) |