Finding CPU usage from top command
I'm currently using
top -b -d 1 > file1.csv
to append the entire output to a csv file. However, I'd like the Cpu(%us) field alone to be entered in file1. I've gotten as far as this:
top -b -d 1|grep Cpu
where I'm able to view only the Cpu entry.
When I try
top -b -d 1|grep Cpu > file1.csv
it doesn't deem to work as I'm not even able to view my file.
My intention is to plot a LiveGraph for all the CPU values (stored in a csv file) dynamically. Thanks!
For total CPU usage:
If you ONLY want the CPU Usage in general you might try this:
top -b -d1 -n1|grep -i "Cpu(s)"|head -c21|cut -d ' ' -f3|cut -d '%' -f1 > file1.csv
This will give you only the CPU value and update the one in the file. If you want to APPEND the data to the file (since I see you are naming it a csv file) then instead of one > use two, like >> file1.csv
.
For each thread and CPU usage:
First you need to eliminate the rest of the columns so it is easier to get the CPU data.
- Run
top
and press f. - In this menu you select which columns you want to see and which you do not. For your case leave only the CPU column and name (if you want the name)
- Press ESC to go back to the main Top menu and save with Capital W the change. Now you command is easier to parse.
Now for general CPU usage you normally have other tools like ps
, iostat
an doing a cat /proc/stat
. For each you need a different parse like the one used for top. I only posted here for TOP since you explicitly mention it in the title.
NOTE: Should be noted that top is not the most efficient way to see the CPU usage or to work with when parsing values for it. For some, using f2 in the cut command shows the value, for others the f3
I'm thinking that using top
may not be the best approach. I would look at using /proc/stat instead. I found an article called "Calculating CPU Usage from /proc/stat" that may just solve most of the problem for you.
It takes a little while, because there seems to be a buffer that needs to be filled up before the pipes start to work.
Try with a small number of iterations first (note: -n2 means 2 iterations):
top -b -d1 -n2 | grep Cpu | cut -c 35-39
Regarding to your comment: If you redirect standard output to a file with top -b -d 1 > file.csv
, you cannot pipe standard output into the grep command.
See:
echo "Standard output" | grep "out"
vs.
echo "Standard output" >/tmp/foo | grep "out"
In the second case you do not have any output.