admin 管理员组

文章数量: 887020

一、获取系统内存使用率

//内存使用率;使用方法:getMemoryUsage()
//原理,直接调用windows.h中的系统api
#include <windows.h>
#include <iostream>
using namespace std;
  
DWORD getMemoryUsgae()
{  
 
    MEMORYSTATUS ms;
    ::GlobalMemoryStatus(&ms);
 
    return ms.dwMemoryLoad;
} 
 
 
void main()
{
    DWORD dwValue=getMemoryUsgae();
    printf("内存使用率为: %d%%",dwValue);
}

二、获取系统CPU使用率


//CPU使用率;使用方法:直接调用getCpuUsage()函数
//原理:记录一定时间内CPU的空闲时间和繁忙时间,然后计算得出
__int64 CompareFileTime ( FILETIME time1, FILETIME time2 )
{
       __int64 a = time1.dwHighDateTime << 32 | time1.dwLowDateTime ;
       __int64 b = time2.dwHighDateTime << 32 | time2.dwLowDateTime ;

       return   (b - a);
}
int getCpuUsage()
{
	HANDLE hEvent;
	BOOL res ;

	FILETIME preidleTime;
	FILETIME prekernelTime;
	FILETIME preuserTime;

	FILETIME idleTime;
	FILETIME kernelTime;
	FILETIME userTime;

	res = GetSystemTimes( &idleTime, &kernelTime, &userTime );

	preidleTime = idleTime;
	prekernelTime = kernelTime;
	preuserTime = userTime ;

	hEvent = CreateEvent (NULL,FALSE,FALSE,NULL); // 初始值为 nonsignaled ,并且每次触发后自动设置为nonsignaled

    WaitForSingleObject( hEvent,1000 ); //等待500毫秒
    res = GetSystemTimes( &idleTime, &kernelTime, &userTime );
    int idle = CompareFileTime( preidleTime,idleTime);
    int kernel = CompareFileTime( prekernelTime, kernelTime);
    int user = CompareFileTime(preuserTime, userTime);
	int cpu = (kernel +user - idle) *100/(kernel+user);
    int cpuidle = ( idle) *100/(kernel+user);
    //cout << "CPU利用率:" << cpu << "%" << "      CPU空闲率:" <<cpuidle << "%" <<endl;
    preidleTime = idleTime;
    prekernelTime = kernelTime;
    preuserTime = userTime ;
	return cpu;
}


本文标签: 使用率 内存 Windows cpu