How do I calculate CPU usage percentage? – Linux Tips And Tricks

How do I calculate CPU usage percentage? – Linux Tips And Tricks

HomeOther ContentHow do I calculate CPU usage percentage? – Linux Tips And Tricks
ChannelPublish DateThumbnail & View CountActions
Channel AvatarPublish Date not found Thumbnail
0 Views
Learn how to calculate CPU usage percentage in Linux.

The /proc/stat file keeps track of a variety of different statistics about the system since it was last restarted.

grep ‘cpu ‘ /proc/stat
OUTPUT
cpu 6992 1362 21245 11173867 914 0 2498 0 0 0

The number shown next to the cpu is the amount of time, measured in jiffies (1/100ths of a second on most architectures, use sysconf(_SC_CLK_TCK) to obtain the right value), that the system (/”cpu/” line) or the specific CPU (/”cpuN/” line) spent in various states:

The very first /”cpu/” line aggregates the numbers in all of the other /”cpuN/” lines.
From left to right.
user: normal processes executing in user mode
nice: same as user processes but executing in as a low priority
system: processes executing in kernel mode
idle: twiddling thumbs
iowait: waiting for I/O to complete
irq: servicing interrupts (hardware irq)
softirq: servicing softirqs

The /”intr/” line gives counts of interrupts serviced since boot time.
The /”ctxt/” line gives the total number of context switches across all CPUs.
The /”btime/” line gives the time at which the system booted, in seconds since the Unix epoch.
The /”processes/” line gives the number of processes and threads created, which includes (but is not limited to) those created by calls to the fork() and clone() system calls.
The /”procs_running/” line gives the number of processes currently running on CPUs.
The /”procs_blocked/” line gives the number of processes currently blocked, waiting for I/O to complete.
The /”softirq/” is the software version of the hardware interrupts.

To calculate the percentage of cpu used by system processes, use this command.
grep ‘cpu ‘ /proc/stat | awk ‘{usage=($4)*100/($2+$3+$4+$5+$6+$7+$8+$9+$10+$11)} END {print usage /”%/”}’

#linux #ubuntu #redhat #bash

Please take the opportunity to connect and share this video with your friends and family if you find it useful.