Files
fastfetch/src/modules/cpuUsage.c
T

49 lines
1.7 KiB
C
Raw Normal View History

2021-11-24 16:16:25 +08:00
#include "fastfetch.h"
#include <unistd.h>
#define FF_CPU_USAGE_MODULE_NAME "CPU Usage"
#define FF_CPU_USAGE_NUM_FORMAT_ARGS 1
void ffPrintCPUUsage(FFinstance* instance)
{
long user, nice, system, idle, iowait, irq, softirq;
2022-05-23 20:01:18 +02:00
FILE* procStat = fopen("/proc/stat", "r");
2021-11-24 16:16:25 +08:00
if(procStat == NULL)
{
2022-06-17 18:15:36 +02:00
ffPrintError(instance, FF_CPU_USAGE_MODULE_NAME, 0, &instance->config.cpu, "fopen(\"""/proc/stat\", \"r\") == NULL");
2021-11-24 16:16:25 +08:00
return;
}
if (fscanf(procStat, "cpu%ld%ld%ld%ld%ld%ld%ld", &user, &nice, &system, &idle, &iowait, &irq, &softirq) < 0) goto exit;
long workJiffies1 = user + nice + system;
long totalJiffies1 = workJiffies1 + idle + iowait + irq + softirq;
sleep(1);
rewind(procStat);
if (fscanf(procStat, "cpu%ld%ld%ld%ld%ld%ld%ld", &user, &nice, &system, &idle, &iowait, &irq, &softirq) < 0) goto exit;
long workJiffies2 = user + nice + system;
long totalJiffies2 = workJiffies2 + idle + iowait + irq + softirq;
// https://stackoverflow.com/questions/3017162/how-to-get-total-cpu-usage-in-linux-using-c#answer-3017438
long workOverPeriod = workJiffies2 - workJiffies1;
long totalOverPeriod = totalJiffies2 - totalJiffies1;
double cpuPercent = (double)workOverPeriod / (double)totalOverPeriod * 100;
2022-06-17 18:15:36 +02:00
if(instance->config.cpuUsage.outputFormat.length == 0)
2021-11-24 16:16:25 +08:00
{
2022-06-17 18:15:36 +02:00
ffPrintLogoAndKey(instance, FF_CPU_USAGE_MODULE_NAME, 0, &instance->config.cpuUsage.key);
2021-11-24 16:16:25 +08:00
printf("%.2lf%%\n", cpuPercent);
}
else
{
2022-06-17 18:15:36 +02:00
ffPrintFormat(instance, FF_CPU_USAGE_MODULE_NAME, 0, &instance->config.cpuUsage, FF_CPU_USAGE_NUM_FORMAT_ARGS, (FFformatarg[]){
2021-11-24 16:16:25 +08:00
{FF_FORMAT_ARG_TYPE_DOUBLE, &cpuPercent}
});
}
exit:
fclose(procStat);
}