Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C API for getting CPU load in linux

Tags:

c++

c

linux

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.

  • Doesn't need to be portable
  • Must not require any libraries beyond a base RHEL4 installation.
like image 862
kdt Avatar asked Jul 29 '09 07:07

kdt


People also ask

How check CPU usage in Linux terminal?

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.

How do I get total CPU usage on Linux C++?

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.


2 Answers

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.

like image 200
dmckee --- ex-moderator kitten Avatar answered Oct 21 '22 18:10

dmckee --- ex-moderator kitten


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.

like image 25
indy Avatar answered Oct 21 '22 18:10

indy