Files
fastfetch/src/detection/cpuusage/cpuusage.c
T

75 lines
2.2 KiB
C
Raw Normal View History

#include "fastfetch.h"
2023-03-17 17:56:31 +08:00
#include "detection/cpuusage/cpuusage.h"
#include "common/time.h"
#include <stdint.h>
2023-10-10 16:00:23 +08:00
static FFlist cpuTimes1;
static uint64_t startTime;
2026-03-29 09:28:49 +08:00
void ffPrepareCPUUsage(void) {
2026-04-14 10:41:18 +08:00
if (startTime != 0) {
2026-03-29 09:28:49 +08:00
return; // Already prepared
}
2026-04-14 10:41:18 +08:00
ffListInit(&cpuTimes1);
2023-10-10 16:00:23 +08:00
ffGetCpuUsageInfo(&cpuTimes1);
startTime = ffTimeGetNow();
}
2026-03-29 09:28:49 +08:00
const char* ffGetCpuUsageResult(FFCPUUsageOptions* options, FFlist* result) {
2026-07-10 18:08:04 +08:00
const char* error = nullptr;
2026-04-14 10:41:18 +08:00
if (startTime == 0) {
ffListInit(&cpuTimes1);
2023-10-10 16:00:23 +08:00
error = ffGetCpuUsageInfo(&cpuTimes1);
2026-03-29 09:28:49 +08:00
if (error) {
return error;
}
ffTimeSleep(options->waitTime);
2026-03-29 09:28:49 +08:00
} else {
uint64_t elapsedTime = ffTimeGetNow() - startTime;
2026-03-29 09:28:49 +08:00
if (elapsedTime < options->waitTime) {
ffTimeSleep(options->waitTime - (uint32_t) elapsedTime);
}
}
2026-03-29 09:28:49 +08:00
if (cpuTimes1.length == 0) {
return "No CPU cores found";
}
2023-10-10 16:00:23 +08:00
2026-04-14 10:41:18 +08:00
FF_LIST_AUTO_DESTROY cpuTimes2 = ffListCreate();
2023-11-01 15:26:24 +08:00
uint32_t retryCount = 0;
2023-10-10 16:00:23 +08:00
retry:
error = ffGetCpuUsageInfo(&cpuTimes2);
2026-03-29 09:28:49 +08:00
if (error) {
return error;
}
if (cpuTimes1.length != cpuTimes2.length) {
return "Unexpected CPU usage result";
}
2023-10-10 16:00:23 +08:00
2026-03-29 09:28:49 +08:00
for (uint32_t i = 0; i < cpuTimes1.length; ++i) {
2024-10-25 14:48:11 +08:00
FFCpuUsageInfo* cpuTime1 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes1, i);
FFCpuUsageInfo* cpuTime2 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes2, i);
2026-03-29 09:28:49 +08:00
if (cpuTime2->totalAll <= cpuTime1->totalAll) {
if (++retryCount <= 3) {
2023-11-01 15:36:13 +08:00
ffListClear(&cpuTimes2);
ffTimeSleep(options->waitTime);
2023-11-01 15:36:13 +08:00
goto retry;
}
return "CPU time did not increase. Try increasing wait time.";
2023-10-10 16:00:23 +08:00
}
}
2026-03-29 09:28:49 +08:00
for (uint32_t i = 0; i < cpuTimes1.length; ++i) {
2024-10-25 14:48:11 +08:00
FFCpuUsageInfo* cpuTime1 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes1, i);
FFCpuUsageInfo* cpuTime2 = FF_LIST_GET(FFCpuUsageInfo, cpuTimes2, i);
2026-04-14 10:41:18 +08:00
*FF_LIST_ADD(double, *result) = (double) (cpuTime2->inUseAll - cpuTime1->inUseAll) / (double) (cpuTime2->totalAll - cpuTime1->totalAll) * 100;
2023-10-10 16:00:23 +08:00
cpuTime1->inUseAll = cpuTime2->inUseAll;
cpuTime1->totalAll = cpuTime2->totalAll;
2022-11-15 17:48:57 +08:00
}
startTime = ffTimeGetNow();
2026-07-10 18:08:04 +08:00
return nullptr;
}