Plotting CPU and Ram utilization

I want to plot the CPU and memory utilisation of an Apache server hosted in Raspberry Pi 3B+ with Raspbian Stretch in it. For that I have followed the procedure mentioned here. The instructions work fine in a Ubuntu Desktop with the modification, top -p $PID -bn 1 in place of top -p $PID -bMn 1 in file. But using the same in Raspberry Pi, it fails to extract the CPU and memory info. On further studying, I found out that the instruction, egrep '^[0-9]+' is not working in Raspberry Pi. What could be the possible reason? And how can I achieve my goal if I have to find any alternative?

Answers 1

  • egrep is just a shell script that runs grep -E. grep, egrep, and fgrep are a family of commands that share the same binary and man page. Your egrep is probably finding nothing because it is trying to match a number at the start of the line (the process id) in the output from top, but instead there are spaces in front of the number.

    The article you link to must be using a different version of top to you, with slight differences in output. This is not untypical for commands that are meant to be used interactively. Nonetheless, I used the following command on my Raspberry Pi to get the wanted data:

    top -p "${1?pid}" -b -d 1 |
    awk '$1~/[0-9]/{print systime(),$6,$9;fflush()}' > top.dat

    I've simplified the code: instead of a while loop, top runs continuously with an interval of 1 second (-d 1). Instead of egrep, awk looks for a number ([0-9]) in the first column ($1) of the output. Instead of date, awk uses its built-in systime() function. The output of awk is buffered, so when you interrupt the script to stop it, a lot of data that hasn't yet been written to the file can be lost. The fflush() avoids this.

    If this doesn't work for you, try replacing awk by gawk. You may need to install gawk. (A simpler minimal awk may have been installed by default).

    Note that the script is collecting columns 6 ($6) and 9. You may need or want to change this depending on the top output. My version shows these headers:


    so $6 is RES which is the resident memory usage. $5 might be more appropriate, the total virtual memory. Both these values are in kibibytes (*1024) and do not seem to get m and g suffixes as in the linked article. To get around this I changed the gnuplot script to replace




    I also changed the first line to

    #!/usr/bin/gnuplot -c

    as I couldn't get gnuplot to accept -preview with -c. You may not need to do this.

Related Questions