48

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.

1
  • Forgot to mention: delay argument for top is also useless to me... Jun 10, 2010 at 18:13

7 Answers 7

103

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%

7
  • Can this be easily adopted to find the usage of a specific process? May 7, 2012 at 17:52
  • 1
    The technique is similar but not exactly the same. You can get process-specific data from the /proc/<pid>/stat file (see 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, 2012 at 9:51
  • 1
    What about this answer: stackoverflow.com/a/9229580/582917 It also uses proc/stat, but no need for an interval. Jul 19, 2014 at 9: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, 2016 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, 2016 at 12:01
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

2
  • That won't do... I am looking for an actual percentage. I do not see how I could calculate it from that Jun 10, 2010 at 18:24
  • 1
    This answer is wrong, the numbers in /proc/loadavg are also affected by I/O.
    – scai
    Aug 12, 2016 at 11:15
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.

3
  • 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... Jun 10, 2010 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 Nov 21, 2013 at 13:20
  • 1
    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, 2015 at 5:27
6

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
2
  • 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. Nov 11, 2019 at 10:24
  • It means your CPU usage was at 66% during one second.
    – souch
    Nov 29, 2021 at 8:20
1

cat /proc/stat

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

2
  • 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? Jun 10, 2010 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, 2010 at 18:32
0

I suggest two files to starting...

/proc/stat and /proc/cpuinfo.

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

0

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
----------------------------------------------
1
  • 2
    Dead link. Is not a valid answer.
    – e-info128
    Sep 1, 2022 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.