50

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.

jww
  • 97,681
  • 90
  • 411
  • 885
David Polák
  • 1,581
  • 4
  • 18
  • 33

7 Answers7

107

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%

starball
  • 20,030
  • 7
  • 43
  • 238
Hitobat
  • 2,847
  • 1
  • 16
  • 12
  • Can this be easily adopted to find the usage of a specific process? – fIwJlxSzApHEZIl May 07 '12 at 17:52
  • 1
    The technique is similar but not exactly the same. You can get process-specific data from the /proc//stat file (see http://www.linuxhowtos.org/manpages/5/proc.htm for details). Cpu usage data is contained in the utime and stime fields, as a number of clock ticks (rather than jiffies). Therefore you need to work out how many clock ticks were available between your 2 readings, which you can usually approximate by finding the clock frequency using sysconf. – Hitobat Jun 28 '12 at 09:51
  • 1
    What about this answer: http://stackoverflow.com/a/9229580/582917 It also uses proc/stat, but no need for an interval. – CMCDragonkai Jul 19 '14 at 09:34
  • @Hitobat Aren't jiffy and clock ticks same thing, so it should be fine to deal with data in /proc/pid/stat the same way as in /proc/stat ? If not, how can we convert clock ticks to jiffy or vice-versa ? – pranavk Mar 10 '16 at 20:05
  • @CMCDragonkai The answer in your link returns the *overall* CPU usage since starting the program. *This* answer returns the *current* CPU usage of the process. – scai Aug 14 '16 at 12:01
  • 1
    this doesn't give correct answer and output is not similar to `top`'s. you should use `idle time`( fourth column) instead of first three values and then : (difference of total times - difference of idle times) / difference of total times. – fa7eme Sep 29 '20 at 08:03
  • 1
    Shouldn't `work_jiffies` sum up more values, like `work_jiffies = user + nice + system + iowait + irq + softirq`?. – scai Jun 07 '21 at 10:23
7

cpu-stat is a C++ project that permits to read Linux CPU counter from /proc/stat .

Get CPUData.* and CPUSnaphot.* files from cpu-stat's src directory.

Quick implementation to get overall cpu usage:

#include "CPUSnapshot.h"

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  CPUSnapshot previousSnap;
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  CPUSnapshot curSnap;
  
  const float ACTIVE_TIME = curSnap.GetActiveTimeTotal() - previousSnap.GetActiveTimeTotal();
  const float IDLE_TIME   = curSnap.GetIdleTimeTotal() - previousSnap.GetIdleTimeTotal();
  const float TOTAL_TIME  = ACTIVE_TIME + IDLE_TIME;
  int usage = 100.f * ACTIVE_TIME / TOTAL_TIME;
  std::cout << "total cpu usage: " << usage << " %" << std::endl;
}

Compile it:

g++ -std=c++11 -o CPUUsage main.cpp CPUSnapshot.cpp CPUData.cpp
souch
  • 181
  • 2
  • 3
  • 1
    Hi, I tried this part in my program and it gives 66. Can you please explain what does that mean? My program takes 2 second to complete it's execution and after that it gave 66 which I didn't understood what that means. So please help me out. – Aparajit Garg Nov 11 '19 at 10:24
  • It means your CPU usage was at 66% during one second. – souch Nov 29 '21 at 08:20
  • why not use GetTotalTimeTotal() for total time? – memory of a dream Apr 26 '23 at 12:33
6

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

wdebeaum
  • 4,101
  • 1
  • 22
  • 12
6

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.

Relevant documentation: man getloadavg and man 5 proc

N.B. Load average, usual to *NIX systems, can be more than 100% (per CPU/core) because it actually measures number of processes ready to be run by scheduler. With Windows-like CPU metric, when load is at 100% you do not really know whether it is optimal use of CPU resources or system is overloaded. Under *NIX, optimal use of CPU loadavg would give you value ~1.0 (or 2.0 for dual system). If the value is much greater than number CPU/cores, then you might want to plug extra CPUs into the box.

Otherwise, dig the /proc file system.

Dummy00001
  • 16,630
  • 5
  • 41
  • 63
  • Interesting, I have just let the computer Idle for one minute, With top at 70 second delay. Top showed 95% idle over that minute. and When I read loadavg it showed me 0.20 which is when divided 10% of usage, This method is way too unprecise for me. Most I can afford is 1% error... – David Polák Jun 10 '10 at 18:42
  • I have a system in which the average load values are very high. Take a use case and see that the formula suggested above is way inaccurate: first load figure from /proc/loadavg is 159.47 -> multiplied -> 15900 -> divided by 8 (core, as reported in /proc/stat) gives me a load of 1987.5 . Sounds reasonable to you to simply truncate it to 100? Not to me... :-) . This problem is more complex. The load figures in /proc/loadavg are dependent on the number of processes on the system and seemigly overwhelmed systems can be very responsive. Take a look at 'collectl' command line tool – Boaz Rymland Nov 21 '13 at 13:20
  • 2
    This method is actually gives you processor queue length per CPU. Even though it is a good measure for overall system load, it does not represent the actual CPU load. For example, if your CPU does a lot of `iowait` the queue length will go up when actual CPU usage goes down. – dtoux Jan 20 '15 at 05:27
1

cat /proc/stat

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

Anycorn
  • 50,217
  • 42
  • 167
  • 261
  • This looks more like it could work... but what is the total capacity of cpu per one second? should I calculate with clock of the cpu? Or how do I know what total increment of, lets say 125, translates into usage? – David Polák Jun 10 '10 at 18:27
  • @dav compute elapsed cpu time, compute time spent in user/system/whatever mode, get ratio , for example cpu_user/cpu_ticks. – Anycorn Jun 10 '10 at 18:32
0

I suggest two files to starting...

/proc/stat and /proc/cpuinfo.

http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt

Lauro Oliveira
  • 2,362
  • 1
  • 18
  • 12
-2

have a look at this C++ Lib.

The information is parsed from /proc/stat. it also parses memory usage from /proc/meminfo and ethernet load from /proc/net/dev

----------------------------------------------
current CPULoad:5.09119
average CPULoad 10.0671
Max     CPULoad 10.0822
Min     CPULoad 1.74111
CPU: : Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
----------------------------------------------
network load: wlp0s20f3 : 1.9kBit/s : 920Bit/s : 1.0kBit/s :  RX Bytes Startup: 15.8mByte TX Bytes Startup: 833.5mByte
----------------------------------------------
memory load: 28.4% maxmemory: 16133792 Kb used: 4581564 Kb  Memload of this Process 170408 KB
----------------------------------------------
fuxey
  • 25
  • 1
  • 5