我正在编写一个代码来获取每个进程百分比的已用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);
答案 0 :(得分: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);
}