xcode 获取运行时的 CPU 使用率 | IOS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11842513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get CPU usage at runtime | iOS
提问by Manish Ahuja
Is there any way I can the get overall CPU usage of an iPhone. I have seen a few apps like Battery Doctor and System Activity Monitor for iPhones which display overall CPU usage.
有什么方法可以获取 iPhone 的整体 CPU 使用率。我见过一些应用程序,例如 iPhone 的 Battery Doctor 和 System Activity Monitor,它们显示整体 CPU 使用情况。
I found a solution, (link to the answer) but it only gives me the CPU usage of my app and not of all the overall apps.
我找到了一个解决方案,(链接到答案)但它只给了我我的应用程序的 CPU 使用率,而不是所有整体应用程序的 CPU 使用率。
回答by holex
please, try this one, it might a good start for you. it has been tested on real device only.
请试试这个,这对你来说可能是一个好的开始。它仅在真实设备上进行了测试。
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!");
}
you also need the following headers as well:
您还需要以下标题:
#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>