0

有很多相同的问题,但我找不到很好的答案。我查看了这个特定帖子中的代码,它给出了每个核心的使用率,但它不准确,即使 Instrument 告诉我一个核心处于满负荷状态(素数测试!),它也总是停留在 14% 左右。

我还阅读了这个问题,我实际上从中得到了代码。

我对此知之甚少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);
    }
}
4

0 回答 0