Instantly share code, notes, and snippets.

Embed
What would you like to do?
#import <mach/mach.h>
double cpu_usage() {
thread_array_t threads;
mach_msg_type_number_t thread_count;
if (task_threads(mach_task_self(), &threads, &thread_count) != KERN_SUCCESS) {
return -1;
}
double total = 0;
for (int i = 0; i < thread_count; i++) {
struct thread_basic_info info;
mach_msg_type_number_t info_count = THREAD_BASIC_INFO_COUNT;
if (thread_info(threads[i], THREAD_BASIC_INFO, (thread_info_t)&info, &info_count) != KERN_SUCCESS) {
return -1;
}
if (!(info.flags & TH_FLAGS_IDLE)) {
total += info.cpu_usage / (double)TH_USAGE_SCALE * 100.0;
}
}
if (vm_deallocate(mach_task_self(), (vm_offset_t)threads, thread_count * sizeof(thread_t)) != KERN_SUCCESS) {
return -1; // memory leak. should never happen.
}
return total;
}
vm_size_t memory_usage_resident() {
struct task_basic_info info;
mach_msg_type_number_t info_count = TASK_BASIC_INFO_COUNT;
if (task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&info, &info_count) != KERN_SUCCESS) {
return -1;
}
return info.resident_size;
}
mach_vm_size_t memory_usage_live_bytes() {
task_vm_info_data_t info;
mach_msg_type_number_t info_count = TASK_VM_INFO_COUNT;
if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &info_count) != KERN_SUCCESS) {
return -1;
}
return info.internal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment