« hitch a ride downtown

Amator Profesionist

Note de subsol, scrise de Skee.

fractal

Using GNUplot to graph process CPU usage

At a friend’s request and out of plain curiosity, I went about trying to find a way to graph per-process CPU usage over time. So I wrote this tiny script that grabs a certain PID’s CPU usage every 3 seconds for however long the user specifies, and when it’s done, it outputs a nice ASCII chart of the CPU usage, courtesy of GNUplot.

Here’s the script:

#!/bin/zsh
if (( ! $# )); then
    echo "Usage: $0:t <PID> <minutes to monitor>" >&2
    return 1;
fi

let "ticks=$2*60/3"
for i in {1..$ticks}; do;
    ps -p $1 -o pcpu | grep -v % >> $1-usage.txt;
    sleep 3;
    echo $i / $ticks;
done;

gnuplot -e "set term dumb; set yrange [0:100]; \
plot '$1-usage.txt' s c;"

And here’s the output:

100 ++------+------+-------+------+-------+------+-------+------+------++
    +       +      +       +      +       +  'usage-mplayer.txt'+****** +
    |                                                                   |
    |                                                                   |
 80 ++                                                                 ++
    |                                                                   |
    |                  *******************                              |
    *******************                  *                        ******|
 60 +*                                   *                      ***    ++
    |                                    *                    **        |
    |                                    *                    *         |
    |                                    *                   *          |
    |                                    *                   *          |
 40 ++                                   *                   *         ++
    |                                    *                   *          |
    |                                    *                  *           |
    |                                    *                  *           |
 20 ++                                   *                  *          ++
    |                                    *                  *           |
    |                                    *******************            |
    +       +      +       +      +       +      +       +      +       +
  0 ++------+------+-------+------+-------+------+-------+------+------++
    0      100    200     300    400     500    600     700    800     900

And GNUplot also does graphical charts! Take the <PID>-usage.txt file dropped in your cwd by the script and run it thru GNUplot like this:

gnuplot -e "set term png; set output graph.png; \
set yrange [0:100]; plot 'PID-usage.txt' s c"

The numbers on the X axis are ticks (seconds/3), the numbers on the Y axis are CPU usage.

Required for this script: zsh, gnuplot and… ps.