公司前一段有個需求就是獲取使用電腦cpu、內(nèi)存等資源占用
就cpu占用而言,獲取方式有計算和直接從pdh性能監(jiān)視器兩種。
這里使用pdh獲得

image.png
最后導(dǎo)出dlll供unity使用
pch.h
#ifndef PCH_H
#define PCH_H
// 添加要在此處預(yù)編譯的標(biāo)頭
#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);
}