How to get CPU usage percent in C++ using the Sigar libraries

▼魔方 西西 提交于 2019-12-23 03:13:35

问题


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;


来源:https://stackoverflow.com/questions/14508275/how-to-get-cpu-usage-percent-in-c-using-the-sigar-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!