方法参考网上的一段代码,把它改成了类以方便调用,很简单,但是可以一用,哈哈。
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) {} void CpuUsage::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 init int CpuUsage::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_; int use_rate = (interval - (ul_sys_idle.QuadPart - cpu_idle_time_)) * 100 / interval; cpu_time_ = ul_sys_kernel.QuadPart + ul_sys_user.QuadPart; cpu_idle_time_ = ul_sys_idle.QuadPart; return use_rate; }
时间: 2024-10-18 19:52:33