CPU使用率



#include <windows.h>  
#include <psapi.h>  
#include <assert.h>  
  
  
  
//Time convert  
static UINT64 file_time_2_utc(const FILETIME* ftime)  
{  
    LARGE_INTEGER li;  
  
    assert(ftime);  
    li.LowPart = ftime->dwLowDateTime;  
    li.HighPart = ftime->dwHighDateTime;  
    return li.QuadPart;  
}  
  
  
// Get CPU numbers
static int get_processor_number()  
{  
    SYSTEM_INFO info;  
    GetSystemInfo(&info);  
    return (int)info.dwNumberOfProcessors;  
}  
    
  
int get_cpu_usage()  
{  
 
    static int processor_count_ = -1;  
 
    static UINT64 last_time_ = 0;  
    static UINT64 last_system_time_ = 0;  
  
  
    FILETIME now;  
    FILETIME creation_time;  
    FILETIME exit_time;  
    FILETIME kernel_time;  
    FILETIME user_time;  
    UINT64 system_time;  
    UINT64 time;  
    UINT64 system_time_delta;  
    UINT64 time_delta;  
  
    int cpu = -1;  
  
  
    if(processor_count_ == -1)  
    {  
        processor_count_ = get_processor_number();  
    }  
  
    GetSystemTimeAsFileTime(&now);  
  
    if (!GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time,  
        &kernel_time, &user_time))  
    {  
        // We don't assert here because in some cases (such as in the Task Manager)  
        // we may call this function on a process that has just exited but we have  
        // not yet received the notification.  
        return -1;  
    }  
    system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time))/processor_count_;  
    time = file_time_2_utc(&now);  
  
    if ((last_system_time_ == 0) && (last_time_ == 0))  
    {  
        // First call, just set the last values.  
        last_system_time_ = system_time;  
        last_time_ = time;  
        return -1;  
    }  
  
    system_time_delta = system_time - last_system_time_;  
    time_delta = time - last_time_;  
   
  
    if (time_delta == 0)  
        return -1;  
  
    // We add time_delta / 2 so the result is rounded.  
    cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta);  
    last_system_time_ = system_time;  
    last_time_ = time;  
    return cpu;  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值