In linux, is there a built-in C library function for getting the CPU load of the machine? Presumably I could write my own function for opening and parsing a file in /proc, but it seems like there ought to be a better way.
You can check how your CPU is being used with the htop command. This prints out real-time information that includes tasks, threads, load average uptime and usage for each CPU. You should see a real-time display with information on how your CPU is being put to use.
Read /proc/cpuinfo to find the number of CPU/cores available to the systems. Call the getloadavg() (or alternatively read the /proc/loadavg ), take the first value, multiply it by 100 (to convert to percents), divide by number of CPU/cores. If the value is greater than 100, truncate it to 100. Done.
If you really want a c interface use getloadavg()
, which also works in unixes without /proc
.
It has a man page with all the details.
The preferred method of getting information about CPU load on linux is to read from /proc/stat, /proc/loadavg and /proc/uptime. All the normal linux utilities like top use this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With