我有一个程序,用于测量特定内核(此处为第二个CPU内核)上进程的消耗CPU时间。有时我得到的值高于100%。
此值的原因是什么? 访问进程的CPU时间时,CPU总时间变化是否这么快? 如何摆脱这种不准确性?
int main(int argc, char **argv)
{
int pid = 1111;
while (true)
{
long unsigned int diffCPUTotal, diffUserCPU, diffSysCPU, diffCuCPU, diffCsCPU, procCPUUsage;
setCPUTotal();
setProcCPU(pid);
diffCPUTotal = cpuTotal - prev_cpuTotal;
diffUserCPU = procUserCPU - prev_procUserCPU;
diffSysCPU = procSysCPU - prev_procSysCPU;
diffCuCPU = procCuCPU - prev_procCuCPU;
diffCsCPU = procCsCPU - prev_procCsCPU;
// Process CPU usage including child processes
procCPUUsage = ((diffUserCPU + diffSysCPU + diffCuCPU + diffCsCPU) / (float) diffCPUTotal) * 100;
printf("Process CPU usage: %lu%%\n", procCPUUsage);
fflush(stdout);
prev_cpuTotal = cpuTotal;
prev_procUserCPU = procUserCPU;
prev_procSysCPU = procSysCPU;
prev_procCuCPU = procCuCPU;
prev_procCsCPU = procCsCPU;
usleep(500000);
}
}
void setCPUTotal()
{
std::ifstream fstat;
fstat.open("/proc/stat", std::ios_base::in);
std::string line;
// Go to desired line
for (int i = 0; i < 3; ++i)
std::getline(fstat, line);
long unsigned int user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice;
// Get statistics of second cpu core
sscanf(line.c_str(), "cpu1 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
&user, &nice, &system, &idle, &iowait, &irq, &softirq, &steal, &guest, &guest_nice);
fstat.close();
// guest and guest_nice are already included user and nice,
// see http://unix.stackexchange.com/q/178045/20626
cpuTotal = user + nice + system + idle + iowait + irq + softirq + steal;
}
void setProcCPU(int pid)
{
std::stringstream ss;
ss << "/proc/" << pid << "/stat";
std::string procStatPath = ss.str();
FILE* fpstat = fopen(procStatPath.c_str(), "r");
fscanf(fpstat, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu"
"%lu %ld %ld %*d %*d %*d %*d %lu %*u %*d",
&procUserCPU, &procSysCPU, &procCuCPU, &procCsCPU, &procStartTime);
fclose(fpstat);
}
答案 0 :(得分:0)
以单核形式报告。
100%表示“一个核心全部”。如果您的计算机具有8核,则最大可能为800%。
如果启用了超线程,则每个超线程都将作为核心。