Track CPU usage of a process with shell script

In order to track the CPU usage of a process I wrote that little script. Feed it with a PID and an output file and it generates some output you can easily use with TikZ/PGF in LaTeX.

You can adjust the step time by changing the $STEP variable.

Note: The time basis is not quite accurate since the calculations take their time which must be added to the actual step time.
However, in my use cases time accuracy was not primary important and thus could be ignored. I'm quite aware that an asynchronous approach would be much more suitable here.

#!/bin/sh

# USAGE:
# ./trackcpu.sh PID FILE
# Example: ./trackcpu.sh 12345 cputrack1.txt

PID=$1
FILE=$2
TIME=0

STEP=1


while true; do
        clear

        CPU=$(ps -p $PID -o %cpu | awk 'FNR == 2' | sed -e 's/^[[:space:]]*//')
        TIME=$(echo "$TIME+$STEP" | bc)
        echo "$TIME $CPU" >> $FILE
        echo "Time: $TIME sec"
        echo "CPU: $CPU %"

        sleep $STEP

done
Buchcover