gpt4 book ai didi

c++ - 如何使用 Sigar 库在 C++ 中获取 CPU 使用率

转载 作者:行者123 更新时间:2023-11-30 04:21:29 27 4
gpt4 key购买 nike

我正在尝试使用 SIGAR 库在 C++ 中获取 CPU 使用百分比,我编写了下面的代码来尝试获取此信息,但出了点问题,我总是得到一个值 0.3... 而不是一个值在 0% 到 100% 之间。如何使用 SIGAR 库获取 CPU 使用百分比?

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

最佳答案

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

我能够使用以下方法得到一些看起来有些准确的东西:

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 库在 C++ 中获取 CPU 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com