Created
September 15, 2019 16:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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