The answer to this question can range from a simple command, to complex monitoring tools, depending on your needs.
You can start by simply running top -b -n 1 >> file.txt
(-b for batch mode, -n 1 for running a single iteration of top) and store the output (appended) in the file.txt. You can filter also "top" output like top -b -n 1 | grep init
to see only the data for the "init" process or top -b -n 1 | grep "init" | head -1 |awk '{print $9}'
to get the 9th column of the init process data (the CPU value).
If you want to use in a shell script, you could:
CPU=$(top -b -n1 | grep "myprocess" | head -1 | awk '{print $9}')
MEM=$(top -b -n1 | grep "myprocess" | head -1 | awk '{print $10}')
Or, with a single execution of top:
read CPU MEM <<<$(top -b -n1 | grep "myprocess" | head -1 | awk '{print $9 " " $10}')
(note that grep, head and awk could be merged in a single awk command but for the shake of simplicity I'm using separate commands).
We used top in this example but there are alternate methods for other metrics (check sar
, iostat
, vmstat
, iotop
, ftop
, and even reading /proc/*).
Now you have a way to access the data (CPU usage). And in our example we are appending it to a text file. But you can use other tools to store the data and even graph them: store in csv and graph with gnuplot/python/openoffice, use monitoring&graping tools like zabbix, rrdtools, cacti, etc. There is a big world of monitoring tools that allow to collect and graph the data like CPU usage, memory usage, disk io, and even custom metrics (number of mysql connections, etc).
EDIT: finally, to specifically answering your question, if you want to keep track of changes easily for a simple test, you can run top -b -n 1 >> /tmp/file.txt
in your /etc/crontab file, by running top every 5 minutes (or any other time interval if you replace the /5 below).
0-59/5 * * * * root top -b -n1 >>/tmp/output.txt
(and a grep + head -1 in the command above if you're only intestered in a single process data).
Note that the output.txt will grow, so if you want to reset it daily or weekly, you can "rm" it with another crontab entry.
Best Answer
In Linux, you can try this:
From
man top
:With OS X, try:
From top OSX manpage: