windows下获取CPU和物理内存使用率

#pragma once

#include <windows.h>


namespace PCState
{
	class GetPCState
	{
	public:
		GetPCState() = default;
		~GetPCState() = default;

	public:
		int GetCPUUsage();
		int GetMemoryUsage();
		int GetTotalUsage();

	private:
		int GetCPUUsage_();
		int GetMemoryUsage_();


	private:
		FILETIME _old_idle_time;
		FILETIME _old_kernel_time;
		FILETIME _old_user_time;

		FILETIME _idle_time;
		FILETIME _kernel_time;
		FILETIME _user_time;
	};
}

#include "PCState.h"
#include <iostream> 



namespace PCState
{
	__int64 CompareFileTime(FILETIME time1, FILETIME time2)
	{
		__int64 a = (__int64)time1.dwHighDateTime << 32 | time1.dwLowDateTime;
		__int64 b = (__int64)time2.dwHighDateTime << 32 | time2.dwLowDateTime;
		return (b - a);
	}

	int GetPCState::GetTotalUsage()
	{
		int cpu = GetCPUUsage();
		int mry = GetMemoryUsage();

		if (cpu >= 90 || mry >= 90){
			return max(cpu, mry);
		}

		return (int)((cpu + mry) / 2);
	}

	int GetPCState::GetCPUUsage()
	{
		int ret = GetCPUUsage_();
		if (ret >= 90){
			printf("<!warning> cpu usage is %d%%.\n", ret);
		}
		return ret;
	}

	int GetPCState::GetMemoryUsage()
	{
		int ret = GetMemoryUsage_();
		if (ret >= 90){
			printf("<!warning> memory usage is %d%%.\n", ret);
		}
		return ret;
	}

	int GetPCState::GetCPUUsage_()
	{
		if (GetSystemTimes(&_idle_time, &_kernel_time, &_user_time) == 0){
			// 获取CPU使用率失败
			printf("get cpu usage failed.\n");
			return 100;
		}

		int idle = (int)CompareFileTime(_old_idle_time, _idle_time);
		int kernel = (int)CompareFileTime(_old_kernel_time, _kernel_time);
		int user = (int)CompareFileTime(_old_user_time, _user_time);
		int cpu = (kernel + user - idle) * 100 / (kernel + user);
		// int cpuidle = (idle)* 100 / (kernel + user);

		_old_idle_time = _idle_time;
		_old_kernel_time = _kernel_time;
		_old_user_time = _user_time;

		return cpu;
	}

	int GetPCState::GetMemoryUsage_()
	{
		MEMORYSTATUSEX statex;
		statex.dwLength = sizeof(statex);
		
		if (GlobalMemoryStatusEx(&statex) == 0){
			// 获取CPU使用率失败
			printf("get memory usage failed.\n");
			return 100;
		}

		int momory = 100 - (int)(((double)statex.ullAvailPhys / (double)statex.ullTotalPhys) * 100);
		return momory;
	}


}


其中一部分代码来自:

http://zhidao.baidu.com/link?url=kjbdGvPmU1L4no4cJlp1yll5udAWTqn-RHPP5rVUrXWOKtQLuQTcI0_nY39Ne9qrqnH72EXyZ1RVBTd8SZNq_a

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值