Skip to content

Instantly share code, notes, and snippets.

@hechen hechen/CPU Usage.m
Created Sep 15, 2019

Embed
What would you like to do?
How to collect the usage of CPU. Collect the usage of each thread.
- (integer_t)checkCPUUsage {
thread_act_array_t threads;
mach_msg_type_number_t threadCount = 0;
const task_t thisTask = mach_task_self_;
kern_return_t ret = task_threads(thisTask, &threads, &threadCount);
if (ret != KERN_SUCCESS) {
return 0;
}
integer_t cpuUsage = 0;
for (int i = 0; i < threadCount; i++) {
thread_info_data_t threadInfo;
thread_basic_info_t threadBasicInfo;
mach_msg_type_number_t threadInfoCount = THREAD_INFO_MAX;
if (thread_info(threads[i], THREAD_BASIC_INFO, threadInfo, &threadInfoCount)) {
threadBasicInfo = (thread_basic_info_t)threadInfo;
if (!(threadBasicInfo->flags & TH_FLAGS_IDLE)) {
cpuUsage += threadBasicInfo->cpu_usage;
}
}
}
assert(vm_deallocate(mach_task_self_, (vm_address_t)threads, threadCount * sizeof(thread_t)) == KERN_SUCCESS);
return cpuUsage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.