It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                已关闭8年。
            
                    
#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>

static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;

// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between
// You'll need to call this at regular intervals, since it measures the load between
// the previous call and the current one.
float GetCPULoad()
{
    host_cpu_load_info_data_t cpuinfo;
    mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
    if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)
    {
        unsigned long long totalTicks = 0;
        for(int i=0; i<CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];
        sysLoadPercentage = CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);
    }
    else return -1.0f;
}

float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
   unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;
   unsigned long long idleTicksSinceLastTime  = idleTicks-_previousIdleTicks;
   float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
   _previousTotalTicks = totalTicks;
   _previousIdleTicks  = idleTicks;
   return ret;
}


我对我希望您能提供帮助的代码有一些疑问:


什么是“ host_cpu_load_info_data_t”结构?这有什么用途?
什么是“ mach_msg_type_number_t”结构?这有什么用途?
预处理程序定义“ HOST_CPU_LOAD_INFO_COUNT”及其用途是什么?
什么是host_statistics函数?
上面列出的host_statistics函数的每个参数是什么意思? (从未见过他们)
什么是预处理器定义CPU_STATE_MAX和CPU_STATE_IDLE?
预处理程序定义KERN_SUCCESS是什么?


如果无法回答,请将我引到包含所有这些答案的站点。我已经尝试过谷歌搜索,但是找不到任何答案,也找不到任何文档。另外,如果问题过于具体,我将删除该问题,但请在这样的问题仍然有效的地方提供一个来源。

谢谢

最佳答案

包含“所有这些答案”的站点是http://www.opensource.apple.com/source/xnu/xnu-1699.24.8/。您可能还会发现Mac OS X Internals一书(由Amit Singh撰写)很有用。

关于c++ - 对某些Unix代码有疑问吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8767504/

10-09 19:17