在运行时获取CPU使用情况| iOS版

有没有什么办法可以获得iPhone的整体CPU使用率。 我看到了一些应用程序,如电池医生和系统活动监视器的iPhone显示总体CPU使用率。

我find了一个解决scheme,( 链接到答案 ),但它只给我我的应用程序的CPU使用率,而不是所有的整体应用程序。

请试试这个,这对你来说可能是一个好的开始。 它仅在真实设备上进行过testing。

processor_info_array_t _cpuInfo, _prevCPUInfo = nil; mach_msg_type_number_t _numCPUInfo, _numPrevCPUInfo = 0; unsigned _numCPUs; NSLock *_cpuUsageLock; 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; _cpuUsageLock = [[NSLock alloc] init]; 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) { Float32 _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: %.2f%%", i, _inUse / _total * 100.f); } [_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 = nil; _numCPUInfo = 0U; } else { NSLog(@"Error!"); } 

您还需要以下标题:

 #import <sys/sysctl.h> #import <sys/types.h> #import <sys/param.h> #import <sys/mount.h> #import <mach/mach.h> #import <mach/processor_info.h> #import <mach/mach_host.h>