Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get total cpu usage in Linux using C++

I am trying to get total cpu usage in %. First I should start by saying that "top" will simply not do, as there is a delay between cpu dumps, it requires 2 dumps and several seconds, which hangs my program (I do not want to give it its own thread)

next thing what I tried is "ps" which is instant but always gives very high number in total (20+) and when I actually got my cpu to do something it stayed at about 20...

Is there any other way that I could get total cpu usage? It does not matter if it is over one second or longer periods of time... Longer periods would be more useful, though.

like image 909
David Polák Avatar asked Jun 10 '10 18:06

David Polák


People also ask

How do I get CPU usage in C?

To get the % CPU usage, you will need to divide it by the # of logical cores that the OS sees. To get get the CPU % usage you would need ( CPU time / # of cores / wall-clock time elapsed ), but otherwise correct.

How much CPU do I have Linux?

Use the cat command to display the data held in /proc/cpuinfo. This command will produce a lot of text, typically it will repeat the same information for the number of cores present in your CPU. A more concise means to get most of this information is via lscpu, a command that lists the CPU details.


2 Answers

cat /proc/stat

http://www.linuxhowtos.org/System/procstat.htm

I agree with this answer above. The cpu line in this file gives the total number of "jiffies" your system has spent doing different types of processing.

What you need to do is take 2 readings of this file, seperated by whatever interval of time you require. The numbers are increasing values (subject to integer rollover) so to get the %cpu you need to calculate how many jiffies have elapsed over your interval, versus how many jiffies were spend doing work.

e.g. Suppose at 14:00:00 you have

cpu 4698 591 262 8953 916 449 531

total_jiffies_1 = (sum of all values) = 16400

work_jiffies_1 = (sum of user,nice,system = the first 3 values) = 5551

and at 14:00:05 you have

cpu 4739 591 289 9961 936 449 541

total_jiffies_2 = 17506

work_jiffies_2 = 5619

So the %cpu usage over this period is:

work_over_period = work_jiffies_2 - work_jiffies_1 = 68

total_over_period = total_jiffies_2 - total_jiffies_1 = 1106

%cpu = work_over_period / total_over_period * 100 = 6.1%

Hope that helps a bit.

like image 51
Hitobat Avatar answered Oct 02 '22 05:10

Hitobat


Try reading /proc/loadavg. The first three numbers are the number of processes actually running (i.e., using a CPU), averaged over the last 1, 5, and 15 minutes, respectively.

http://www.linuxinsight.com/proc_loadavg.html

like image 34
wdebeaum Avatar answered Oct 02 '22 07:10

wdebeaum