TOP

1. Calculate CPU Usage[5]

  • Sample output of top

    top - 13:53:01 up  9:58,  2 users,  load average: 0.02, 0.03, 0.00
    Tasks: 191 total,   1 running, 147 sleeping,   0 stopped,   0 zombie
    %Cpu(s):  1.8 us,  1.8 sy,  0.8 ni, 95.6 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
    KiB Mem :  2035580 total,   348500 free,   764640 used,   922440 buff/cache
    KiB Swap:   998396 total,   985340 free,    13056 used.  1026164 avail Mem 
    
    PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                       
      1 root      20   0  185200   5420   3616 S   0.0  0.3   0:08.01 systemd                                       
      2 root      20   0       0      0      0 S   0.0  0.0   0:00.02 kthreadd                                      
      4 root       0 -20       0      0      0 I   0.0  0.0   0:00.00 kworker/0:0H                                  
      6 root       0 -20       0      0      0 I   0.0  0.0   0:00.00 mm_percpu_wq                                  
      ...
    
  • 13:53:01 current time, consistent with date
  • up 9:58 the uptime of the system (including time spent in syspend), reading from /proc/uptime [2,6]
  • 2 users the number of users
  • load average: 0.02, 0.03, 0.00 load average over the last 1 minute, 5 minutes and 15 minutes respectively [9]
  • Line 2 : see [6]
  • Line 3 :
    • Field Meaning : [7]
    • Calcualted from /proc/stat[1,2,5]
    • /proc/stat [1, 2]
  • Line 4/5 : Read from /proc/meminfo, consistent with free
  • Process info [8] : Combine /proc/stat with /proc/<pid>/stat, we can get CPU usage [5]

2. Source code

  1. First, locate the directory of top by which top (/usr/bin/top);
  2. Then, search the package wrapping top by sudo dpkg -S /usr/bin/top
  3. Download source code : sudo apt-get source procps
  4. You may get the error : “You must put some ‘source’ URIs in your sources.list”
    1. Solution 1 : Uncomment all deb-src ... fields in /etc/apt/sources.list and then update it.
    2. Solution 2 : System Settings -> Software & Updates -> Ubuntu software -> Source code
  5. Or https://github.com/soarpenguin/procps-3.0.5.git

3. Scirpts

  • https://github.com/yongchaoHe/scripts/tree/master/CPU

REF

  1. /proc/stat 解析
  2. proc - process information pseudo-filesystem
  3. How to calculate CPU Usage -/proc/stat vs top
  4. How to read the Linux /proc/stat file
  5. Linux平台Cpu使用率的计算
  6. top工具全字段解析+实战(一)
  7. top工具全字段解析+实战(二)
  8. top工具全字段解析+实战(三)
  9. Understanding the Load Average On Linux and Other Unix-like Systems