系統資訊獲取 5,獲取CPU當前使用率

2021-06-20 10:23:29 字數 1579 閱讀 4071

cpu資源看做是乙個個的時間片,統計cpu使用率也是計算在一段時間內忙碌的時間佔比。

我們知道getsystemtime可以得到當前系統時間,另外乙個名字類似的函式,getsystemtimes可以得到三種不同的時間(自開機以來):空閒時間,核心時間和使用者時間。

函式原型:

bool winapi getsystemtimes(

_out_opt_ lpfiletime lpidletime,

_out_opt_ lpfiletime lpkerneltime,

_out_opt_ lpfiletime lpusertime

);

cpu要麼是在核心態,要麼是在使用者態。相加就是cpu總時間。

所以有以下公式:

cpu使用率 = (核心時間 + 使用者時間 - 空閒時間)/(核心時間 + 使用者時間)。

在較短的間隔時間內,先後兩次呼叫getsystemtimes,然後相減,再使用上面的公式可得出這段時間內的cpu使用率。

#include "stdafx.h"

#include #include using namespace std;

__int64 comparefiletime ( filetime time1, filetime time2 )

int _tmain(int argc, _tchar* argv)

{ handle hevent;

filetime preidletime;

filetime prekerneltime;

filetime preusertime;

getsystemtimes( &preidletime, &prekerneltime, &preusertime );

hevent = createevent (null,false,false,null); // 初始值為 nonsignaled ,並且每次觸發後自動設定為nonsignaled

while (1){

waitforsingleobject( hevent,1000 ); //等待500毫秒

filetime idletime;

filetime kerneltime;

filetime usertime;

getsystemtimes( &idletime, &kerneltime, &usertime );

int idle = comparefiletime( preidletime,idletime);

int kernel = comparefiletime( prekerneltime, kerneltime);

int user = comparefiletime(preusertime, usertime);

int cpu = (kernel +user - idle) *100/(kernel+user);

cout << "cpu利用率:" << cpu << "%" <

cpu資訊獲取

cpu溫度的獲取 cpu溫度儲存在 sys class thermal thermal zone0 temp中,讀取出的數值需要除以1000。bash 工具 cat 工具用來強制讀取乙個檔案。gerp 工具用來篩選資料。awk 用來處理資料。uptime 獲取cpu負載資訊 bash 數值計算 ba...

C 獲取CPU資訊

include windows.h include iostream include string using namespace std 用來儲存資訊 dword deax dword debx dword decx dword dedx void execpuid dword veax 初始化c...

mac獲取cpu資訊

物理cpu數量,可以數不重複的 physical id 有幾個 邏輯cpu數量 物理cpu數量 x cpu cores 這個規格值 x 2 如果支援並開啟ht 備註一下 linux下top檢視的cpu也是邏輯cpu個數 一般來說,物理cpu個數 每顆核數就應該等於邏輯cpu的個數,如果不相等的話,則...