openEuler inclusion category: bugfix bugzilla: https://gitee.com/openeuler/kernel/issues/I4CIJQ CVE: NA
----------------------------------------------------------------------
This tool can help calculate the CPU utilization rate in higher precision.
Signed-off-by: Hongyu Li 543306408@qq.com --- tools/accounting/Makefile | 2 +- tools/accounting/idle_cal.c | 91 +++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 tools/accounting/idle_cal.c
diff --git a/tools/accounting/Makefile b/tools/accounting/Makefile index 03687f19cbb1..d14151e28173 100644 --- a/tools/accounting/Makefile +++ b/tools/accounting/Makefile @@ -2,7 +2,7 @@ CC := $(CROSS_COMPILE)gcc CFLAGS := -I../../usr/include
-PROGS := getdelays +PROGS := getdelays idle_cal
all: $(PROGS)
diff --git a/tools/accounting/idle_cal.c b/tools/accounting/idle_cal.c new file mode 100644 index 000000000000..6d621b37c70e --- /dev/null +++ b/tools/accounting/idle_cal.c @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * idle_cal.c + * + * Copyright (C) 2021 + * + * cpu idle time accouting + */ + + +#include <stdlib.h> +#include <stdio.h> +#include <fcntl.h> +#include <string.h> +#include <unistd.h> +#include <time.h> +#include <limits.h> +#include <sys/time.h> + +#define BUFFSIZE 4096 +#define HZ 100 +#define FILE_NAME "/proc/stat2" + +struct cpu_info { + char name[BUFFSIZE]; + long long value[1]; +}; + +int main(void) +{ + int cpu_number = sysconf(_SC_NPROCESSORS_ONLN); + struct cpu_info *cpus = (struct cpu_info *)malloc(sizeof(struct cpu_info)*cpu_number); + struct cpu_info *cpus_2 = (struct cpu_info *)malloc(sizeof(struct cpu_info)*cpu_number); + + char buf[BUFFSIZE]; + long long sub; + double value; + + while (1) { + FILE *fp = fopen(FILE_NAME, "r"); + int i = 0; + struct timeval start, end; + + + while (i < cpu_number+1) { + int n = fscanf(fp, "%s %lld\n", cpus[i].name, &cpus[i].value[0]); + + if (n < 0) { + printf("wrong"); + return -1; + } + i += 1; + } + + gettimeofday(&start, NULL); + fflush(fp); + fclose(fp); + i = 0; + + sleep(1); + + FILE *fp_2 = fopen(FILE_NAME, "r"); + + while (i < cpu_number+1) { + int n = fscanf(fp_2, "%s %lld\n", cpus_2[i].name, &cpus_2[i].value[0]); + + if (n < 0) { + printf("wrong"); + return -1; + } + i += 1; + } + + gettimeofday(&end, NULL); + fflush(fp); + fclose(fp_2); + + sub = end.tv_sec-start.tv_sec; + value = sub*1000000.0+end.tv_usec-start.tv_usec; + system("reset"); + printf("CPU idle rate %f\n", 1000000/HZ*(cpus_2[0].value[0]-cpus[0].value[0]) + /value); + + for (int i = 1; i < cpu_number+1; i++) { + printf("CPU%d idle rate %f\n", i-1, 1-1000000/HZ + *(cpus_2[i].value[0]-cpus[i].value[0])/value); + } + } + return 0; +} +