-1
모든 코어의 평균 CPU 사용량을 계산하는 프로그램이 있습니다. 모든 코어에 대해 개별적으로 CPU 사용량을 얻기 위해 프로그램을 확장하고 싶습니다. 각 코어마다 개별적으로 수행하는 방법을 이해할 수 없습니다. 감사합니다. .모든 코어의 CPU 사용량을 얻기 위해 C 프로그램을 확장하는 방법
는/proc 디렉토리/합계는 다음과 같이 시작 :
cpu 3698413 14728645 5722454 10134230 69449 0 1223 0 0 0
cpu0 976719 3443648 1547164 2603386 19834 0 411 0 0 0
cpu1 919933 3875010 1438785 2355286 17272 0 373 0 0 0
cpu2 989581 3082865 1559116 2922304 18621 0 169 0 0 0
cpu3 812180 4327122 1177389 2253254 13722 0 270 0 0 0
평균 calcutates 내 프로그램 : 여기
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#define PROCSTATFILE "/proc/stat"
void eprintf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
double cpuusage(void) {
char buf[BUFSIZ];
static unsigned long long lastuser, lastnice, lastsystem, lastidle;
unsigned long long user, nice, system, idle;
unsigned long long total;
double percent;
FILE *fp;
if (lastuser && lastnice && lastsystem && lastidle) {
fp = fopen(PROCSTATFILE, "r");
if (!fp)
eprintf("failed to open %s\n", PROCSTATFILE);
fgets(buf, BUFSIZ, fp);
sscanf(buf, "cpu %llu %llu %llu %llu", &user, &nice, &system, &idle);
fclose(fp);
percent = 0;
total = 0;
total += (user - lastuser);
total += (nice - lastnice);
total += (system - lastsystem);
percent = total;
total += (idle - lastidle);
percent /= total;
percent *= 100;
}
fp = fopen(PROCSTATFILE, "r");
if (!fp)
eprintf("failed to open %s\n", PROCSTATFILE);
fgets(buf, BUFSIZ, fp);
sscanf(buf, "cpu %llu %llu %llu %llu", &lastuser, &lastnice, &lastsystem, &lastidle);
fclose(fp);
return percent;
}
int main(void) {
while (1) {
printf("cpu usage:%f\n", cpuusage());
sleep(1);
}
return EXIT_SUCCESS;
}
당신은'함수 strerror를 printf를해야한다 (errno를)''eprintf'에서 –