C 簡單的CPU使用率監控程式

2021-10-06 11:37:15 字數 2840 閱讀 2913

主要**如下:

// test4.cpp : 定義控制台應用程式的入口點。

// 簡單的監控指定程式列表的cpu使用率

#include "stdafx.h"

#include#include #include #include #include #include #include #include #include #include using namespace std;

typedef struct enumhwndsarg

enumhwndsarg, *lpenumhwndsarg;

handle getprocesshandlebyid(int nid)//通過程序id獲取程序控制代碼

std::vectorgetprocessidbyname(const char* pname)

processentry32 pe = ;

for (bool ret = process32first(hsnapshot, &pe); ret; ret = process32next(hsnapshot, &pe))

} closehandle(hsnapshot);

return vpid;

}bool callback lpenumfunc(hwnd hwnd, lparam lparam)

return true;

}void gethwndsbyprocessid(dword processid, std::vector&vechwnds)

longlong filetime2uint64(const _in_ filetime& fttime)

std::mapgmaplastsystime;

std::mapgmaplastnowtime;

void threadtest()

} fclose(fpin);

char aname[128];

while (1)

; int a = sizeof(pmc);

if (!getprocessmemoryinfo(handle, (process_memory_counters*)&pmc, sizeof(pmc)))

//占用的物理記憶體峰值

sprintf_s(strinfo, "peakworkingsetsize:%d(kb)\n", pmc.peakworkingsetsize / 1024);

//當前占用的物理記憶體

sprintf_s(strinfo, "workingsetsize:%d(kb)\n", pmc.workingsetsize / 1024);

//占用的虛擬記憶體峰值(物理記憶體+頁檔案),對應任務管理器中的commit列值

sprintf_s(strinfo, "peakpagefileusage:%d(kb)\n", pmc.peakpagefileusage / 1024);

//當前占用的虛擬記憶體(物理記憶體+頁檔案),對應任務管理器中的commit列值

sprintf_s(strinfo, "pagefileusage:%d(kb)\n", pmc.pagefileusage / 1024);

//等同於當前占用的虛擬記憶體(物理記憶體+頁檔案),對應任務管理器中的commit列值,並不是任務管理器中的私有獨佔記憶體的意思。

sprintf_s(strinfo, "privateusage:%d(kb)\n", pmc.privateusage / 1024);

//printf("%s", strout.c_str());

filetime ftnow, ftcreate, ftexit, ftkernel, ftuser;

system_info info;

getsysteminfo(&info);

getsystemtimeasfiletime(&ftnow);

if (!getprocesstimes(handle, &ftcreate, &ftexit, &ftkernel, &ftuser))

return;

longlong llsys = (filetime2uint64(ftkernel) + filetime2uint64(ftuser)) / info.dwnumberofprocessors;

longlong llnow = filetime2uint64(ftnow);

if (gmaplastsystime[pid] && gmaplastnowtime[pid])

else

}gmaplastsystime[pid] = llsys;

gmaplastnowtime[pid] = llnow;

}} sleep(1000);

//printf_s("\n\n********************\n"); }}

int main()

配置檔案 load.config:根據實際需要進行配置,比如wechat.exe gameserver.exe webserver.exe

wechat

gameserver

webserver

輸出到 cpu\***xx.log,形式如下

2020-5-25_18:0:14 cpu:0.00 - time:10781641

2020-5-25_18:0:15 cpu:0.00 - time:10468579

2020-5-25_18:0:16 cpu:0.72 - time:10781368

2020-5-25_18:0:17 cpu:0.00 - time:10469099

2020-5-25_18:0:18 cpu:0.00 - time:10781901

獲得cpu的使用率 c )

include include include define systembasicinformation 0 define systemperformanceinformation 2 define systemtimeinformation 3 define li2double x double...

控制CPU使用率

我使用的是ubuntu 14.04版本,用的是自帶的系統監視器來觀察cpu使用率的變化。1.首先來說說怎麼控制cpu使用率,當程式執行乙個死迴圈的時候,使用率就會變成100 而當程式進入idle的時候,使用率就會很低 在別的程式不啟動的情況下 那麼控制cpu使用率就是調整它idle和busy的時間比...

cpu使用率統計

cat proc stat得到 user nice system idle iowait irq softirq stealstolen guest 的9元組 再採兩個夠短的時間點,做差計算即可 cat proc pid stat讀取到 pid 6873 程序號utime 1587 該任務在使用者態...