출처 : http://d.hatena.ne.jp/harukasan/20080825
[sourcecode language="c"]
#include
#include
#include
int main() {
mach_port_t host_port;
host_cpu_load_info_data_t prev_cpu_load, cpu_load;
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
natural_t user, system, idle;
double usage;
host_port = mach_host_self();
host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&prev_cpu_load, &count);
while (1) {
// Cocoa의경우 NSThread를 사용하는 것이 좋습니다.
sleep(1);
// CPU 시간취득
host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&cpu_load, &count);
// 백분율계산
user = cpu_load.cpu_ticks[CPU_STATE_USER] - prev_cpu_load.cpu_ticks[CPU_STATE_USER];
system = cpu_load.cpu_ticks[CPU_STATE_SYSTEM] - prev_cpu_load.cpu_ticks[CPU_STATE_SYSTEM];
idle = cpu_load.cpu_ticks[CPU_STATE_IDLE] - prev_cpu_load.cpu_ticks[CPU_STATE_IDLE];
usage = (double)(user + system) / (system + user + idle) * 100.0;
printf("%f \n", usage);
// 업데이트
prev_cpu_load = cpu_load;
}
return 0;
}
[/sourcecode]