有什么办法可以获取iPhone的总体CPU使用率。我看过一些应用程序,例如Battery Doctor和iPhone的System Activity Monitor,它们显示了总体CPU使用率。

我找到了一个解决方案(link to the answer),但它只为我提供了我的应用程序的CPU使用率,而不是全部应用程序的CPU使用率。

最佳答案

请尝试一下,这可能是一个不错的开始。 ,仅在真实设备上经过测试。

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>

10-08 05:30