Сначала импортируйте все необходимые файлы заголовков в файл интерфейса.
#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;
NSLock *CPUUsageLock;
и в файл реализации.
- (void)cpuSampler:(NSTimer *)timer
{
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) {
[CPUUsageLock lock];
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];
}
if (i == 0) {
NSString *string0 = [NSString stringWithFormat:@"Core: %u Usage: %f%",i,(inUse / total)*100];
}
if (i == 1) {
NSString *string1 = [NSString stringWithFormat:@"Core: %u Usage: %f%",i,(inUse / total)*100];
}
}
[CPUUsageLock unlock];
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;
}
}
NSlog значение для string0 и string1, чтобы узнатьИзмерение ЦП и вызов этого метода через таймер.