Created
May 7, 2025 01:15
-
-
Save jweinst1/c5bd58a39a901dce905e57a7e492bf8c to your computer and use it in GitHub Desktop.
host wide cpu usage on a mac
This file contains hidden or 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
#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