Method refer to a piece of code on the Web, change it to a class to facilitate the call, very simple, but can be used, haha.
Cpu_usage.h
#include <windows.h>class cpuusage {public: cpuusage (); void init (); // Get CPU Usage rate from the last invoke of the function or init int Get (); Private : BOOL Inited_; ULONGLONG Cpu_time_; Ulonglong cpu_idle_time_;};
Cpu_usage.cpp
#include"cpu_usage.h"cpuusage::cpuusage (): Inited_ (false) {}voidCpuusage::init () {FILETIME ft_sys_idle; FILETIME Ft_sys_kernel; FILETIME Ft_sys_user; Ularge_integer Ul_sys_idle; Ularge_integer Ul_sys_kernel; Ularge_integer Ul_sys_user; Getsystemtimes (&ft_sys_idle,/*System Idle time*/&ft_sys_kernel,/*System Kernel time*/&ft_sys_user);/*System User time*/CopyMemory (&ul_sys_idle, &ft_sys_idle,sizeof(FILETIME)); CopyMemory (&ul_sys_kernel, &ft_sys_kernel,sizeof(FILETIME)); CopyMemory (&ul_sys_user, &ft_sys_user,sizeof(FILETIME)); Cpu_time_= Ul_sys_kernel. QuadPart +Ul_sys_user. QuadPart; Cpu_idle_time_=Ul_sys_idle. QuadPart; Inited_=true;}//Get CPU Usage rate from the last invoke of the function or initintCPUUsage::Get() { if(!inited_)return-1; FILETIME Ft_sys_idle; FILETIME Ft_sys_kernel; FILETIME Ft_sys_user; Ularge_integer Ul_sys_idle; Ularge_integer Ul_sys_kernel; Ularge_integer Ul_sys_user; Getsystemtimes (&ft_sys_idle,/*System Idle time*/&ft_sys_kernel,/*System Kernel time*/&ft_sys_user);/*System User time*/CopyMemory (&ul_sys_idle, &ft_sys_idle,sizeof(FILETIME)); CopyMemory (&ul_sys_kernel, &ft_sys_kernel,sizeof(FILETIME)); CopyMemory (&ul_sys_user, &ft_sys_user,sizeof(FILETIME)); Ulonglong interval= Ul_sys_kernel. QuadPart + Ul_sys_user. QuadPart-cpu_time_; intUse_rate = (Interval-(ul_sys_idle. QUADPART-CPU_IDLE_TIME_)) * -/interval; Cpu_time_= Ul_sys_kernel. QuadPart +Ul_sys_user. QuadPart; Cpu_idle_time_=Ul_sys_idle. QuadPart; returnuse_rate;}
Classes for measuring CPU utilization under windows