У меня есть программа, в которой я измеряю потребляемое процессорное время процесса на конкретном ядре (здесь второе ядро процессора).Иногда я получаю значения выше 100%.
В чем причина этого значения?Изменяется ли общее время ЦП при обращении к времени ЦП процесса?Как я могу избавиться от этой неточности?
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);
}