0

我正在编写一个代码来获取每个进程的已用 CPU 百分比,但是我的代码有问题。这会显示奇怪的值,例如 3.63499e+262 % 和 0%,而任务管理器会显示大于 0% 且低于或等于 100% 的值。我做错了什么?

sigar_t *sigarproclist;
sigar_proc_list_t proclist;
sigar_open(&sigarproclist);
sigar_proc_list_get(sigarproclist, &proclist);
for (size_t i = 0; i < proclist.number; i++)
{
    sigar_proc_cpu_t cpu;
    sigar_proc_cpu_get(sigarproclist, proclist.data[i], &cpu);
    sigar_proc_state_t procstate;
    sigar_proc_state_get(sigarproclist, proclist.data[i], &procstate);
    qDebug() << procstate.name << 100 * cpu.percent << "%";
}
sigar_close(sigarproclist);
4

1 回答 1

0

我对我的代码进行了一些更改,现在它看起来有效。

sigar_t *sigarcpulist;
sigar_cpu_info_list_t cpulist;
sigar_open(&sigarcpulist);
sigar_cpu_info_list_get(sigarcpulist, &cpulist);
sigar_close(sigarcpulist);

forever
{
    float percent;
    sigar_t *sigarproclist;
    sigar_proc_list_t proclist;
    sigar_open(&sigarproclist);
    sigar_proc_list_get(sigarproclist, &proclist);
    for (size_t i = 0; i < proclist.number; i++)
    {
        sigar_proc_cpu_t cpu;
        sigar_proc_cpu_get(sigarproclist, proclist.data[i], &cpu);
    }
    Sleep(1000);
    for (size_t i = 0; i < proclist.number; i++)
    {
        sigar_proc_cpu_t cpu;
        int status = sigar_proc_cpu_get(sigarproclist, proclist.data[i], &cpu);
        if (status == SIGAR_OK)
        {
            sigar_proc_state_t procstate;
            sigar_proc_state_get(sigarproclist, proclist.data[i], &procstate);
            percent = cpu.percent * 100 / cpulist.size;
            qDebug() << procstate.name << percent << "%";
        }
    }
    sigar_close(sigarproclist);
}
于 2013-02-23T13:53:31.490 回答