如何获取当前计算机CPU的占用率
1个回答
2018-06-23
展开全部
内存情况比较简单 MEMORYSTATUSEX mstx; mstx.dwLength = sizeof (mstx); GlobalMemoryStatusEx( &mstx ); int iMemeryUsePercentage = mstx.dwMemoryLoad; int iTotalPhysMB = mstx.ullTotalPhys/1024/1024; int iAvailPhysMB = mstx.ullAvailPhys/1024/1024; int iTotalPageFileMB = mstx.ullTotalPageFile/1024/1024; int iAvailPageFileMB = mstx.ullAvailPageFile/1024/1024; char LogBuff[128]; memset( LogBuff , 0 , 128 ); sprintf( LogBuff , "MemAvailPct=%d%% Phys=%d/%d PageFile=%d/%d" , 100 - iMemeryUsePercentage , iAvailPhysMB , iTotalPhysMB , iAvailPageFileMB , iTotalPageFileMB ); printf("%s\n",LogBuff); 以上程序分别输出可用百分比,可以用物理内存/总物理内存,可用页面文件/总页面文件获取CPU的比较复杂,我这边只有获取单个进程CPU占用的方法,不过可以遍历所有进程分别获取再求和就是整个cpu占用率了。 #include #include typedef long long int64_t; typedef unsigned long long uint64_t; /// 时间转换 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的核数 static int get_processor_number() { SYSTEM_INFO info; GetSystemInfo(&info); return (int)info.dwNumberOfProcessors; } int get_cpu_usage(int pid) { //cpu数量 static int processor_count_ = -1; //上一次的时间 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 -1; } system_time_delta = system_time - last_system_time_; time_delta = time - last_time_; if (time_delta == 0) return -1; cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta); last_system_time_ = system_time; last_time_ = time; return cpu; } int main() { while(1) { int cpu; // 参数为进程id cpu = get_cpu_usage(5160); printf("CPU使用率: %d%%\n",cpu); Sleep(1000); } return 0; }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询