请教下:C语言获取计算机系统CPU使用率,内存使用情况的思路或流程是怎样的?!
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请教下:C语言获取计算机系统CPU使用率,内存使用情况的思路或流程是怎样的?!相关的知识,希望对你有一定的参考价值。
网上很多代码雷同,大多不能正确运行,第一次编写有些地方还看不懂,因作业里面用到,请高手赐教,有代码发我下!非常感谢!
内存情况比较简单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 <stdio.h>
#include <Windows.h>
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;
参考技术A 查WINDOW提供的接口是什么,然后用C去调用获取当前数值,就好了,然后设置一个轮询,每间隔一段时间轮询一次就好了。追问
有代码的话,发我下代码呗,省去麻烦。
.
Windows下用C语言获取系统的CPU利用率内存使用率硬盘使用率等
最近在做一个网管软件用C语言获取的系统的一些参数,其中包括系统时间,系统运行时间,系统版本,CPU利用率,内存使用率,硬盘使用率,CPU风扇转速等参数,整理代码如下:
#include <stdio.h>
#include <Windows.h>
#include<time.h>
#include <tchar.h>
#define DIV 1024
#define WIDTH 7
#define GB(x) (((x).HighPart << 2) + ((DWORD)(x).LowPart) / 1024.0 / 1024.0 / 1024.0)
#pragma warning(disable: 4996)
#define true 1
typedef unsigned char U_CHAR;
//获取系统时间
int getSystemTime(char* buffer)
char buf[128];
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buf, sizeof(buf), "Now is %Y-%m-%d %H:%M:%S", timeinfo);
strcpy(buffer,buf);
//CPU利用率
FILETIME m_preidleTime;
FILETIME m_prekernelTime;
FILETIME m_preuserTime;
__int64 CompareFileTime2(FILETIME time1, FILETIME time2)
__int64 a = time1.dwHighDateTime << 32 | time1.dwLowDateTime;
__int64 b = time2.dwHighDateTime << 32 | time2.dwLowDateTime;
return b - a;
void GetCpuUseage()
GetSystemTimes(&m_preidleTime, &m_prekernelTime, &m_preuserTime);
Sleep(1000);
double CpuUseage()
FILETIME idleTime;
FILETIME kernelTime;
FILETIME userTime;
GetSystemTimes(&idleTime, &kernelTime, &userTime);
int idle = CompareFileTime2(m_preidleTime, idleTime);
int kernel = CompareFileTime2(m_prekernelTime, kernelTime);
int user = CompareFileTime2(m_preuserTime, userTime);
if (kernel + user == 0)
return 0.0;
//(总的时间-空闲时间)/总的时间=占用cpu的时间就是使用率
double cpu = abs((kernel + user - idle) * 100 / (kernel + user));
m_preidleTime = idleTime;
m_prekernelTime = kernelTime;
m_preuserTime = userTime;
return cpu;
//读取操作系统的名称
void GetSystemName(char* osname)
char buf[128];
SYSTEM_INFO info; //用SYSTEM_INFO结构判断64位AMD处理器
GetSystemInfo(&info); //调用GetSystemInfo函数填充结构
OSVERSIONINFOEX os;
os.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
strcpy(buf, "unknown OperatingSystem.");
if (GetVersionEx((OSVERSIONINFO *)&os))
//下面根据版本信息判断操作系统名称
switch (os.dwMajorVersion)//判断主版本号
case 4:
switch (os.dwMinorVersion)//判断次版本号
case 0:
if (os.dwPlatformId == VER_PLATFORM_WIN32_NT)
strcpy(buf, "Microsoft Windows NT 4.0"); //1996年7月发布
else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
strcpy(buf, "Microsoft Windows 95");
break;
case 10:
strcpy(buf, "Microsoft Windows 98");
break;
case 90:
strcpy(buf, "Microsoft Windows Me");
break;
break;
case 5:
switch (os.dwMinorVersion) //再比较dwMinorVersion的值
case 0:
strcpy(buf, "Microsoft Windows 2000"); //1999年12月发布
break;
case 1:
strcpy(buf, "Microsoft Windows XP"); //2001年8月发布
break;
case 2:
if (os.wProductType == VER_NT_WORKSTATION
&& info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
strcpy(buf, "Microsoft Windows XP Professional x64 Edition");
else if (GetSystemMetrics(SM_SERVERR2) == 0)
strcpy(buf, "Microsoft Windows Server 2003"); //2003年3月发布
else if (GetSystemMetrics(SM_SERVERR2) != 0)
strcpy(buf, "Microsoft Windows Server 2003 R2");
break;
break;
case 6:
switch (os.dwMinorVersion)
case 0:
if (os.wProductType == VER_NT_WORKSTATION)
strcpy(buf, "Microsoft Windows Vista");
else
strcpy(buf, "Microsoft Windows Server 2008"); //服务器版本
break;
case 1:
if (os.wProductType == VER_NT_WORKSTATION)
strcpy(buf, "Microsoft Windows 7");
else
strcpy(buf, "Microsoft Windows Server 2008 R2");
break;
break;
//if(GetVersionEx((OSVERSIONINFO *)&os))
strcpy(osname, buf);
int main()
//获取系统时间
char buffer[128];
getSystemTime(buffer);
puts(buffer);
//系统运行时间
clock_t start, finish;
double duration;
start = clock();
while (true)
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
Sleep(1000);
printf("%.0f 秒\\n", duration);
//系统版本名称
char osname[20];
GetSystemName(osname);
printf("%s\\n", osname);
//CPU利用率
while (true)
U_CHAR sysStateCpu[5];
double cpu = CpuUseage();
sprintf((char*)sysStateCpu, "%.2lf", cpu);
printf("CPU使用率:%s%%\\n", sysStateCpu);
Sleep(1000);
//内存使用率
char bufPreCPU[5];
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
sprintf(bufPreCPU, "%ld%%\\n", statex.dwMemoryLoad);
puts(bufPreCPU);
//硬盘使用率 调用windows API
ULARGE_INTEGER FreeBytesAvailableC, TotalNumberOfBytesC, TotalNumberOfFreeBytesC;
ULARGE_INTEGER FreeBytesAvailableD, TotalNumberOfBytesD, TotalNumberOfFreeBytesD;
ULARGE_INTEGER FreeBytesAvailableE, TotalNumberOfBytesE, TotalNumberOfFreeBytesE;
ULARGE_INTEGER FreeBytesAvailableF, TotalNumberOfBytesF, TotalNumberOfFreeBytesF;
GetDiskFreeSpaceEx(_T("C:"), &FreeBytesAvailableC, &TotalNumberOfBytesC, &TotalNumberOfFreeBytesC);
GetDiskFreeSpaceEx(_T("D:"), &FreeBytesAvailableD, &TotalNumberOfBytesD, &TotalNumberOfFreeBytesD);
GetDiskFreeSpaceEx(_T("E:"), &FreeBytesAvailableE, &TotalNumberOfBytesE, &TotalNumberOfFreeBytesE);
GetDiskFreeSpaceEx(_T("F:"), &FreeBytesAvailableF, &TotalNumberOfBytesF, &TotalNumberOfFreeBytesF);
/*参数 类型及说明
lpRootPathName String,不包括卷名的磁盘根路径名
lpFreeBytesAvailableToCaller LARGE_INTEGER,指定一个变量,用于容纳调用者可用的字节数量
lpTotalNumberOfBytes LARGE_INTEGER,指定一个变量,用于容纳磁盘上的总字节数
lpTotalNumberOfFreeBytes LARGE_INTEGER,指定一个变量,用于容纳磁盘上可用的字节数
适用平台
Windows 95 OSR2,Windows NT 4.0*/
float totalHardDisk = GB(TotalNumberOfBytesC) + GB(TotalNumberOfBytesD) + GB(TotalNumberOfBytesE) + GB(TotalNumberOfBytesF);
float freeHardDisk = GB(TotalNumberOfFreeBytesC) + GB(TotalNumberOfFreeBytesD) + GB(TotalNumberOfFreeBytesE) + GB(TotalNumberOfFreeBytesF);
float hardDiskUsage = 1- freeHardDisk / totalHardDisk;
//CPU风扇转速
printf("hello world!\\n");
system("pause");
以上是关于请教下:C语言获取计算机系统CPU使用率,内存使用情况的思路或流程是怎样的?!的主要内容,如果未能解决你的问题,请参考以下文章
Python如何获取Android系统下某一个APP的CPU,内存的使用情况
请问怎么用c语言获取电脑(windows)的cpu,内存,硬盘利用率等信息?Linux系统一样吗?
Python如何获取Android系统下某一个APP的CPU,内存的使用情况