Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
CPU使用率取得DLL
//--------------------------------------------------------
#include <windows.h>
#include <windowsx.h>
#include <pdh.h>
#pragma comment (lib, "Pdh.lib") // Pdh.lib使うよ
//-------------------------------------------------------- Exportする
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport)void StartCPUUsage(DWORD dwTimer);
__declspec(dllexport)long GetCPUUsage(void);
#ifdef __cplusplus
}
#endif
//-------------------------------------------------------- これはExportしない
void CPUUsageThread(void);
//-------------------------------------------------------- グローバル
long lCPUUsage = 0; // CPU使用率
DWORD dwInterval = 0; // 何m秒毎に取るのか
HANDLE hThread = NULL;
HQUERY hQuery = NULL;
//--------------------------------------------------------
BOOL WINAPI DllMain (HINSTANCE hInstance, DWORD fdwReason, LPVOID lpvReserved)
{
switch(fdwReason){
case DLL_PROCESS_ATTACH: // DLLロードされた
// 準備
PdhOpenQuery(NULL, 0, &hQuery);
break;
case DLL_PROCESS_DETACH: // DLLアンロードされた
if(hThread != NULL){
// スレッド終了
TerminateThread(hThread, 0);
}
if(hQuery != NULL){
// PDH終了
PdhCloseQuery(hQuery);
}
break;
}
return TRUE;
}
//-------------------------------------------------------- 測定開始
__declspec(dllexport)void StartCPUUsage(DWORD dwTimer)
{
dwInterval = dwTimer;
DWORD dwThreadID = 0;
// スレッドにする
CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)CPUUsageThread, NULL, 0, &dwThreadID);
}
//-------------------------------------------------------- 測定しまくり
void CPUUsageThread(void)
{
HCOUNTER hCounter;
PDH_FMT_COUNTERVALUE counter;
// CPU使用率を永遠に取ってみる
PdhAddCounter(hQuery, TEXT("\\Processor(_Total)\\% Processor Time"), 0, &hCounter);
while (1) {
PdhCollectQueryData(hQuery);
Sleep(dwInterval);
PdhCollectQueryData(hQuery);
PdhGetFormattedCounterValue(hCounter, PDH_FMT_LONG, NULL, &counter);
lCPUUsage = counter.longValue;
}
}
//-------------------------------------------------------- CPU使用率教える
__declspec(dllexport)long GetCPUUsage(void)
{
// 今の値を返す
return lCPUUsage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment