Skip to content

Instantly share code, notes, and snippets.

@icpz
Created November 27, 2019 10:51
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 icpz/8c160c2b628d59db0b65ae247f63b4a5 to your computer and use it in GitHub Desktop.
Save icpz/8c160c2b628d59db0b65ae247f63b4a5 to your computer and use it in GitHub Desktop.
get cpu usage in percent of current process on darwin
#include <mach/bootstrap.h>
#include <mach/mach_host.h>
#include <mach/mach_port.h>
#include <mach/task.h>
#include <mach/mach_vm.h>
#include <mach/thread_act.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
float get_self_cpu_usage(void) {
kern_return_t ret;
thread_act_array_t threads;
mach_msg_type_number_t tcnt;
int cpuusg = 0;
int i;
ret = task_threads(mach_task_self(), &threads, &tcnt);
if (ret != KERN_SUCCESS) {
return -1.0;
}
for (i = 0; i < tcnt; ++i) {
thread_basic_info_data_t info;
mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
ret = thread_info(threads[i], THREAD_BASIC_INFO, (thread_info_t)&info, &count);
if (ret != KERN_SUCCESS) {
continue;
}
if (!(info.flags & TH_FLAGS_IDLE)) {
cpuusg += info.cpu_usage;
}
(void)mach_port_deallocate(mach_task_self(), threads[i]);
}
(void)mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)(uintptr_t)threads, tcnt * sizeof(*threads));
return (float)cpuusg / TH_USAGE_SCALE * 100.0;
}
void *thcb(void *arg) {
int i;
for (i = 0; i < 0x7FFFFFFF; ++i) {
;
}
return NULL;
}
int main() {
pthread_t th;
pthread_create(&th, NULL, thcb, NULL);
sleep(1);
printf("cpu usage: %.4f\n", get_self_cpu_usage());
pthread_join(th, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment