Last active
November 21, 2022 20:14
-
-
Save fibasile/5403374 to your computer and use it in GitHub Desktop.
getting CPU usage in macosx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/sysctl.h> | |
#include <sys/types.h> | |
#include <mach/mach.h> | |
#include <mach/processor_info.h> | |
#include <mach/mach_host.h> | |
processor_info_array_t cpuInfo, prevCpuInfo; | |
mach_msg_type_number_t numCpuInfo, numPrevCpuInfo; | |
unsigned numCPUs; | |
int mib[2U] = { CTL_HW, HW_NCPU }; | |
size_t sizeOfNumCPUs = sizeof(numCPUs); | |
int status = sysctl(mib, 2U, &numCPUs, &sizeOfNumCPUs, NULL, 0U); | |
if(status) | |
numCPUs = 1; | |
// in a timed loop | |
natural_t numCPUsU = 0U; | |
kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUsU, &cpuInfo, &numCpuInfo); | |
if(err == KERN_SUCCESS) { | |
for(unsigned i = 0U; i < numCPUs; ++i) { | |
float inUse, total; | |
if(prevCpuInfo) { | |
inUse = ( | |
(cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER]) | |
+ (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM]) | |
+ (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]) | |
); | |
total = inUse + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]); | |
} else { | |
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]; | |
total = inUse + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]; | |
} | |
NSLog(@"Core: %u Usage: %f",i,inUse / total); | |
} | |
if(prevCpuInfo) { | |
size_t prevCpuInfoSize = sizeof(integer_t) * numPrevCpuInfo; | |
vm_deallocate(mach_task_self(), (vm_address_t)prevCpuInfo, prevCpuInfoSize); | |
} | |
prevCpuInfo = cpuInfo; | |
numPrevCpuInfo = numCpuInfo; | |
cpuInfo = NULL; | |
numCpuInfo = 0U; | |
} else { | |
// error | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
extracted from http://stackoverflow.com/questions/6785069/get-cpu-percent-usage?lq=1