#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;
}
I have a few questions about the code which I was hoping you could help me out with:
- What is a “host_cpu_load_info_data_t” structure? What is it used for?
- What is a “mach_msg_type_number_t” structure? What is it used for?
- What is the preprocessor definition “HOST_CPU_LOAD_INFO_COUNT” and its use?
- What is the host_statistics function?
- What do each of the arguments listed above for the host_statistics function mean? (never seen them before)
- What is the preprocessor definition CPU_STATE_MAX and CPU_STATE_IDLE?
- What is the preprocessor definition KERN_SUCCESS?
If not possible to answer, please reference me to a site that contains ALL these answers. I already tried googling it but couldn’t find any answers, nor could I find any documentation. Also, if the question is too specific I will delete the question, please suggest a source where a question like this would be valid though.
Thanks
The site that contains “ALL these answers” is http://www.opensource.apple.com/source/xnu/xnu-1699.24.8/. You might also find the book Mac OS X Internals (by Amit Singh) useful.