summaryrefslogtreecommitdiffstats
path: root/src/detection/cpuusage/cpuusage_apple.c
blob: 50a8b15b4a0d56ece0d69e9e653d3064d6a97389 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "fastfetch.h"
#include "detection/cpuusage/cpuusage.h"

#include <mach/processor_info.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>

const char* ffGetCpuUsageInfo(FFlist* cpuTimes) {
    natural_t numCPUs = 0U;
    processor_info_array_t cpuInfo;
    mach_msg_type_number_t numCpuInfo;

    if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUs, &cpuInfo, &numCpuInfo) != KERN_SUCCESS) {
        return "host_processor_info() failed";
    }
    if (numCPUs * CPU_STATE_MAX != numCpuInfo) {
        return "Unexpected host_processor_info() result";
    }

    for (natural_t i = 0U; i < numCPUs; ++i) {
        integer_t inUse = cpuInfo[CPU_STATE_MAX * i + CPU_STATE_USER] + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_SYSTEM] + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_NICE];
        integer_t total = inUse + cpuInfo[CPU_STATE_MAX * i + CPU_STATE_IDLE];

        FFCpuUsageInfo* info = FF_LIST_ADD(FFCpuUsageInfo, *cpuTimes);
        *info = (FFCpuUsageInfo) {
            .inUseAll = (uint64_t) inUse,
            .totalAll = (uint64_t) total,
        };
    }

    vm_deallocate(mach_task_self(), (vm_address_t) cpuInfo, numCpuInfo * sizeof(integer_t));
    return NULL;
}