2012-01-07 175 views
-1
#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; 
} 

我有,我希望你能幫助我的代碼了幾個問題:關於一些unix代碼的問題?

  • 什麼是「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?

如果無法回答,請將我引至包含所有這些答案的網站。我已經嘗試使用Google搜索,但無法找到任何答案,也找不到任何文檔。此外,如果問題太具體,我會刪除該問題,請建議一個來源,這樣的問題將是有效的。

感謝

+0

Unix的版本和風格? – 2012-01-07 05:04:03

+0

Mac OSX Snow Leopard – fdh 2012-01-07 05:05:12

回答

0

包含 「所有這些問題的答案」 是http://www.opensource.apple.com/source/xnu/xnu-1699.24.8/網站。你也可以找到這本書Mac OS X內部件(由阿米特辛格)有用。

+0

我已經簽出了這兩個源代碼,但並沒有真正理解代碼。我希望得到解釋,而不僅僅是源代碼。 – fdh 2012-01-07 05:34:25