如何在C ++中使用Sigar库获取CPU使用率 [英] How to get CPU usage percent in C++ using the Sigar libraries

查看:1360
本文介绍了如何在C ++中使用Sigar库获取CPU使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用SIGAR库获得c ++中的CPU使用百分比,我写下面的代码试图获取这些信息,但有些事是错误的,我总是得到一个值0.3 ...而不是一个值在0%至100%之间。如何获得使用SIGAR库的CPU使用率百分比?

I'm trying to get the CPU usage percent in c++ using the SIGAR libraries, i wrote the code below to try to get this information, but something is wrong, i always got a value 0.3... instead of a value between 0% to 100 %. How to get the CPU usage percent with the SIGAR libraries?

#include <QDebug>
#include <sigar.h>
extern "C" 
{
#include <sigar_format.h>
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    sigar_cpu_t cpu1;
    sigar_cpu_t cpu2;
    sigar_cpu_perc_t perc;
    sigar_cpu_perc_calculate(&cpu1, &cpu2, &perc);
    qDebug() << perc.combined;

    return a.exec();
}


推荐答案

strong>:
我不是 Sigar 专家,这是我第一次听到它提到。从我从代码中可以看出, sigar_cpu_perc_calculate 根据cpu的两个快照之间的差异确定负载,不使用两个不同的CPU。

Edit: I am not a Sigar expert, it's the first time I hear it mentioned. From what I could figure out from the code, sigar_cpu_perc_calculate determines the load based on a difference between two "snapshots" of the cpu, not using two different CPUs.

我可以使用下面的方法看起来有些准确:

I was able to have something that looked somewhat accurate using the following:

sigar_t *sigar_cpu;
sigar_cpu_t old;
sigar_cpu_t current;

sigar_open(&sigar_cpu);
sigar_cpu_get(sigar_cpu, &old);

sigar_cpu_perc_t perc;

while(1)
{
    sigar_cpu_get(sigar_cpu, &current);
    sigar_cpu_perc_calculate(&old, &current, &perc);

    std::cout << "CPU " << perc.combined * 100 << "%\n";
    old = current;
    Sleep(100);
}

sigar_close(sigar_cpu);
return 0;

这篇关于如何在C ++中使用Sigar库获取CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆