User Tools

Site Tools


en:ressources:astuces:cpu_process_usage

Calculate the CPU usage of a single process in Linux

The script below calculates the CPU usage of a single process. It does so by parsing the stat file in /proc/<pid> and dividing it with the total cpu usage from /proc/stat.

#!/usr/bin/env bash

# calculate the cpu usage of a single process
# jvehent oct.2013

[ -z $1 ] && echo "usage: $0 <pid>"

sfile=/proc/$1/stat
if [ ! -r $sfile ]; then echo "pid $1 not found in /proc" ; exit 1; fi

proctime=$(cat $sfile|awk '{print $14}')
totaltime=$(grep '^cpu ' /proc/stat |awk '{sum=$2+$3+$4+$5+$6+$7+$8+$9+$10; print sum}')

echo "time                        ratio      cpu%"

while [ 1 ]; do
    sleep 1
    prevproctime=$proctime
    prevtotaltime=$totaltime
    proctime=$(cat $sfile|awk '{print $14}')
    totaltime=$(grep '^cpu ' /proc/stat |awk '{sum=$2+$3+$4+$5+$6+$7+$8+$9+$10; print sum}')
    ratio=$(echo "scale=2;($proctime - $prevproctime) / ($totaltime - $prevtotaltime)"|bc -l)
    echo "$(date --rfc-3339=seconds);  $ratio;      $(echo "$ratio*100"|bc -l)"
done

sample output:

# /root/cpuprocess.sh 31282
time                        ratio      cpu%
2013-10-18 14:14:49+02:00;  .06;      6.00
2013-10-18 14:14:50+02:00;  .13;      13.00
2013-10-18 14:14:51+02:00;  .13;      13.00
2013-10-18 14:14:52+02:00;  .20;      20.00
2013-10-18 14:14:53+02:00;  .24;      24.00
2013-10-18 14:14:54+02:00;  .19;      19.00
2013-10-18 14:14:55+02:00;  0;      0
2013-10-18 14:14:56+02:00;  .13;      13.00
2013-10-18 14:14:57+02:00;  .14;      14.00
2013-10-18 14:14:58+02:00;  .16;      16.00
2013-10-18 14:14:59+02:00;  .16;      16.00
2013-10-18 14:15:00+02:00;  .20;      20.00
2013-10-18 14:15:01+02:00;  .21;      21.00
2013-10-18 14:15:02+02:00;  .12;      12.00
2013-10-18 14:15:03+02:00;  .03;      3.00
2013-10-18 14:15:04+02:00;  .17;      17.00
2013-10-18 14:15:05+02:00;  .14;      14.00
2013-10-18 14:15:06+02:00;  .16;      16.00
2013-10-18 14:15:07+02:00;  .14;      14.00
2013-10-18 14:15:09+02:00;  .17;      17.00
2013-10-18 14:15:10+02:00;  .21;      21.00
2013-10-18 14:15:11+02:00;  .11;      11.00
2013-10-18 14:15:12+02:00;  .07;      7.00
2013-10-18 14:15:13+02:00;  .17;      17.00
2013-10-18 14:15:14+02:00;  .16;      16.00
2013-10-18 14:15:15+02:00;  .17;      17.00
2013-10-18 14:15:16+02:00;  .16;      16.00
2013-10-18 14:15:17+02:00;  .20;      20.00
2013-10-18 14:15:18+02:00;  .17;      17.00
2013-10-18 14:15:19+02:00;  .09;      9.00
2013-10-18 14:15:20+02:00;  .07;      7.00
2013-10-18 14:15:21+02:00;  .15;      15.00
2013-10-18 14:15:22+02:00;  .16;      16.00
2013-10-18 14:15:23+02:00;  .10;      10.00
2013-10-18 14:15:24+02:00;  .09;      9.00
en/ressources/astuces/cpu_process_usage.txt · Last modified: 2024/04/17 10:19 by 127.0.0.1