How to get CPU usage percent in C++ using the Siga

2019-06-05 05:14发布

问题:

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();
}

回答1:

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;