2021-11-24 16:16:25 +08:00
|
|
|
#include "fastfetch.h"
|
2022-07-25 13:15:01 +02:00
|
|
|
#include "common/printing.h"
|
2022-09-21 10:47:15 +08:00
|
|
|
#include "detection/cpuUsage/cpuUsage.h"
|
2022-09-27 22:06:53 +08:00
|
|
|
#include "sys/time.h"
|
2021-11-24 16:16:25 +08:00
|
|
|
|
|
|
|
|
#define FF_CPU_USAGE_MODULE_NAME "CPU Usage"
|
|
|
|
|
#define FF_CPU_USAGE_NUM_FORMAT_ARGS 1
|
|
|
|
|
|
2022-09-27 22:06:53 +08:00
|
|
|
time_t getTimeInMs()
|
|
|
|
|
{
|
|
|
|
|
struct timeval timeNow;
|
|
|
|
|
gettimeofday(&timeNow, NULL);
|
|
|
|
|
return (timeNow.tv_sec * 1000) + (timeNow.tv_usec / 1000);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static long inUseAll1, totalAll1, startTime;
|
|
|
|
|
|
|
|
|
|
void ffPrepareCPUUsage()
|
|
|
|
|
{
|
|
|
|
|
startTime = getTimeInMs();
|
|
|
|
|
ffGetCpuUsageInfo(&inUseAll1, &totalAll1);
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-24 16:16:25 +08:00
|
|
|
void ffPrintCPUUsage(FFinstance* instance)
|
|
|
|
|
{
|
2022-09-27 22:06:53 +08:00
|
|
|
const char* error = NULL;
|
|
|
|
|
if(startTime == 0)
|
|
|
|
|
{
|
|
|
|
|
error = ffGetCpuUsageInfo(&inUseAll1, &totalAll1);
|
|
|
|
|
if(error)
|
|
|
|
|
goto error;
|
|
|
|
|
nanosleep(&(struct timespec){ 1, 0 }, NULL);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
time_t duration = getTimeInMs() - startTime;
|
|
|
|
|
if(duration < 1000)
|
|
|
|
|
nanosleep(&(struct timespec){ 0, (1000 - duration) * 1000000L }, NULL);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
long inUseAll2, totalAll2;
|
|
|
|
|
error = ffGetCpuUsageInfo(&inUseAll2, &totalAll2);
|
2022-09-21 10:47:15 +08:00
|
|
|
|
|
|
|
|
if(error)
|
2021-11-24 16:16:25 +08:00
|
|
|
{
|
2022-09-27 22:06:53 +08:00
|
|
|
error:
|
2022-09-21 10:47:15 +08:00
|
|
|
ffPrintError(instance, FF_CPU_USAGE_MODULE_NAME, 0, &instance->config.cpu, "%s", error);
|
2021-11-24 16:16:25 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2022-09-27 22:06:53 +08:00
|
|
|
double cpuPercent = (double)(inUseAll2 - inUseAll1) / (double)(totalAll2 - totalAll1) * 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}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|