Skip to content

Instantly share code, notes, and snippets.

@jweinst1
Created May 7, 2025 01:15
Show Gist options
  • Save jweinst1/c5bd58a39a901dce905e57a7e492bf8c to your computer and use it in GitHub Desktop.
Save jweinst1/c5bd58a39a901dce905e57a7e492bf8c to your computer and use it in GitHub Desktop.
host wide cpu usage on a mac
#include <stdio.h>
#include <mach/mach.h>
#include <mach/mach_host.h>
int main() {
// Get the host's CPU statistics
host_cpu_load_info_data_t cpu_info;
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
kern_return_t kr = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpu_info, &count);
if (kr != KERN_SUCCESS) {
fprintf(stderr, "host_statistics failed: %s\n", mach_error_string(kr));
return 1;
}
// Calculate the total CPU usage
unsigned long long total = cpu_info.cpu_ticks[CPU_STATE_USER] +
cpu_info.cpu_ticks[CPU_STATE_SYSTEM] +
cpu_info.cpu_ticks[CPU_STATE_IDLE] +
cpu_info.cpu_ticks[CPU_STATE_NICE];
unsigned long long total_used = cpu_info.cpu_ticks[CPU_STATE_USER] +
cpu_info.cpu_ticks[CPU_STATE_SYSTEM] +
cpu_info.cpu_ticks[CPU_STATE_NICE];
double cpu_usage = (double)total_used / total * 100.0;
printf("CPU Usage: %.2f%%\n", cpu_usage);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment