以下內(nèi)容主要來(lái)自http://www.sizeof.cn/html/2010/365.html ,對(duì)其中的一些細(xì)節(jié)進(jìn)行了調(diào)整。
最近在項(xiàng)目中需要監(jiān)測(cè)某個(gè)進(jìn)程的CPU使用率,原本以為是一個(gè)很簡(jiǎn)單的需求,想用Windows上的性能計(jì)數(shù)器來(lái)進(jìn)行計(jì)算的,但是經(jīng)過(guò)嘗試之后,發(fā)現(xiàn)Windows性能計(jì)數(shù)器算出來(lái)的值根本不正確,不耐經(jīng)過(guò)互聯(lián)網(wǎng)的搜索,終于發(fā)現(xiàn)了以下計(jì)算方法,總的測(cè)試,發(fā)現(xiàn)結(jié)果還是比較精準(zhǔn)的。
其實(shí)Windows的進(jìn)程使用率是計(jì)算出來(lái)的,在一段很短的時(shí)間內(nèi),計(jì)算某進(jìn)程使用CPU的時(shí)間,除以所有進(jìn)程使用CPU的時(shí)間,即為該進(jìn)程的CPU使用率。具體代碼如下:#include <stdafx.h>
#include <stdio.h>
#include <Windows.h>
#include <iostream>
using namespace std;
typedef long long int64_t;
typedef unsigned long long uint64_t;
/// 時(shí)間轉(zhuǎn)換
static uint64_t file_time_2_utc(const FILETIME* ftime)
{
LARGE_INTEGER li;
li.LowPart = ftime->dwLowDateTime;
li.HighPart = ftime->dwHighDateTime;
return li.QuadPart;
}
/// 獲得CPU的核數(shù)
static int get_processor_number()
{
SYSTEM_INFO info;
GetSystemInfo(&info);
return (int)info.dwNumberOfProcessors;
}
int get_cpu_usage(int pid)
{
//cpu數(shù)量
static int processor_count_ = -1;
//上一次的時(shí)間
static int64_t last_time_ = 0;
static int64_t last_system_time_ = 0;
FILETIME now;
FILETIME creation_time;
FILETIME exit_time;
FILETIME kernel_time;
FILETIME user_time;
int64_t system_time;
int64_t time;
int64_t system_time_delta;
int64_t time_delta;
int cpu = -1;
if(processor_count_ == -1)
{
processor_count_ = get_processor_number();
}
GetSystemTimeAsFileTime(&now);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
{
return -1;
}
system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time))
/ processor_count_;
time = file_time_2_utc(&now);
if ((last_system_time_ == 0) || (last_time_ == 0))
{
last_system_time_ = system_time;
last_time_ = time;
return get_cpu_usage(pid);
}
system_time_delta = system_time - last_system_time_;
time_delta = time - last_time_;
if (time_delta == 0)
return get_cpu_usage(pid);
cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta);
last_system_time_ = system_time;
last_time_ = time;
return cpu;
}
int main()
{
int cpu;
int process_id;
// 參數(shù)為進(jìn)程id
cin>>process_id;
while(1)
{
cpu = get_cpu_usage(process_id);
printf("CPU使用率: %d%%\n",cpu);
Sleep(1000);
}
return 0;
}