July 07, 2014, 7:38 PM — The top command is one of the most commonly used tools for getting a quick glimpse at performance on a Unix system. It can tell you which processes are gobbling your CPU, which are using too much memory, and what your workload looks like. The output is easy to understand and the command is flexible.
For examining performance beyond the "here and now", on the other hand, top is rarely anyone's choice, but it does provide an option that will let you capture performance data in an automated fashion and is very flexible about big a sample of performance data that it collects.
The first thing to look at to use the top command in a non-immediate (i.e., "batch") fashion is the -b option. You won't want to use this as the only option, however, as the command would then run in a quick loop (every 3 seconds or so) and itself become one of the more prominent tasks you'll be looking at in your captured output. Instead, use the -d (delay) option to specify how much time you want to wait between each iteration of the top command. And to limit how many iterations that your top command will go through, use the -n (number of iterations) option.
A top command that will run every 15 seconds for 4 iterations in batch mode would look like this:
$ top -b -d 15 -n 4
Of course, running that command in the middle of the night through cron isn't likely to be very useful unless you do something with the output so that you can examine it when you want to take a look at what was happening when you were asleep. Redirect the output to a file and all four performance data samples will be waiting for you.
$ top -b -d 15 -n 4 > /tmp/top$$
This command will work on the command line, creating a file with a name like /tmp/top20753. To turn it into a cron job, just specify when you want it to run with a cron line like this:
0 1 * * * /usr/bin/top -b -d 15 -n 4 > /tmp/top$$
This command would save four samples of top output starting at 1 AM. Obviously, you could capture and save as many samples as you feel you might need to evaluate how your system is reponding to processing demands during hours that you're not at your desk. You might, for example, get an idea how much of a load backups or other overnight processing are placing on your system.
Another benefit of using top's batch mode is that ti shows you all of the running processes, not just the top 20 or so that you see when you just type top. Try top -b -n 1 and you will see what I mean.
flickr / Nick Rice