如何获得iOS CPU核心使用?

时间:2013-03-25 15:40:51

标签: ios cpu-usage sysctl

有很多相同的问题,但我找不到很好的答案。我查看了来自this特定帖子的代码,它给出了每个核心的使用情况,但它是不准确的,即使当仪器告诉我一个核心处于满载状态时(primality test!),它总是停留在14%左右。

我还阅读了this我真正从中得到代码的问题。

我对sysctl知之甚少,这似乎是这类事情的关键。有人可以向我解释如何实现这一点,代码示例将更加受到重视。谢谢!

这是我当前的代码,它是在一个单独的线程上运行的,我刚才意识到这可能是一个问题,任何人都可以确认吗? (我使用NSThread和NSNotificationCenter将使用信息发送到主线程。)

- (void)updateCPUUsage
{
    NSMutableArray* arrayOfCPUUsage = [NSMutableArray array];
    while ( 1 )
    {
        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];
                }
                [arrayOfCPUUsage addObject:@(_inUse / _total)];
            }

            [_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;
        }
        [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"CPUUsageUpdate" object:[arrayOfCPUUsage copy]]];
        [arrayOfCPUUsage removeAllObjects];
        usleep(1000);
    }
}

0 个答案:

没有答案