Skip to content

Instantly share code, notes, and snippets.

@hechen
Created September 15, 2019 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hechen/a06a9712d1df4bad6b484a1c45c8c631 to your computer and use it in GitHub Desktop.
Save hechen/a06a9712d1df4bad6b484a1c45c8c631 to your computer and use it in GitHub Desktop.
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