公司前一段有个需求就是获取使用电脑cpu、内存等资源占用
就cpu占用而言,获取方式有计算和直接从pdh性能监视器两种。
这里使用pdh获得
最后导出dlll供unity使用
pch.h
#ifndef PCH_H
#define PCH_H
// 添加要在此处预编译的标头
#include "framework.h"
#endif //PCH_H
#include "pdh.h"
#pragma comment(lib,"pdh.lib")
extern "C" __declspec(dllexport) void InitStart(bool& res);
extern "C" __declspec(dllexport) double GetCurrentCpuValue();
extern "C" __declspec(dllexport) void CloseCPUQuery();
pch.cpp
static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;
void InitStart(bool& res) {
PDH_STATUS status = PdhOpenQuery(NULL, NULL, &cpuQuery);
if (status == ERROR_SUCCESS)
{
status = PdhAddCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
if (status == ERROR_SUCCESS)
{
status = PdhCollectQueryData(cpuQuery);
if (status == ERROR_SUCCESS)
{
res = true;
}
}
}
}
double GetCurrentCpuValue() {
double resVlaue = 0;
PDH_FMT_COUNTERVALUE counterVal;
PDH_STATUS status = PdhCollectQueryData(cpuQuery);
if (status == ERROR_SUCCESS)
{
status = PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
if (status == ERROR_SUCCESS)
{
resVlaue = counterVal.doubleValue;
}
}
return resVlaue;
}
void CloseCPUQuery()
{
PdhRemoveCounter(cpuTotal);
PdhCloseQuery(cpuQuery);
}