Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by process name and log CPU usage

Tags:

linux

unix

Is there an option for linux top command where i can filter processes by name and write the CPU usage of that process every 1 second to a log file?

like image 930
BalaB Avatar asked Jan 03 '12 10:01

BalaB


People also ask

How do I monitor a single process in Linux?

The top Command. Usually, we can use the Linux built-in top command. This command displays a real-time view of a running system in the command prompt. If we want to have an idea of a single process, we can use the -p parameter.

What command displays the CPU utilization for individual processes?

The top command monitors CPU utilization, process statistics, and memory utilization. The top section contains information related to overall system status – uptime, load average, process counts, CPU status, and utilization statistics for both memory and swap space.

How do I sort CPU utilization in Linux?

To sort all running processes by CPU utilization, simply press Shift+P key.


2 Answers

top & pgrep

To filter the output of top by process name, you can use pgrep to get a list of PIDs by process name then pass them to the -p option of top.

For example:

top -p $(pgrep -d',' http) 

Note: the -d',' option delimits the PIDs with commas, which is what is expected by the top -p. Note 2: top will return a failure message if there are no running processes that match the name you specify in pgrep.

To write the results of top to a file, use the -n 1 option (only one iteration) and redirect the output to your log file.

top -p $(pgrep -d',' http) -n 1 >> your_log_file 

To do that every second, perhaps a while loop with a sleep would do?

while :; do top -p $(pgrep -d',' http) -n 1 >> your_log_file; sleep 1; done 

To timestamp each entry, you can append the output of date. E.g.

while :; do top -p $(pgrep -d',' http) -n 1 >> log.txt; date >> log.txt; sleep 1; done 
like image 121
Shawn Chin Avatar answered Sep 28 '22 09:09

Shawn Chin


Another option is:

top -b -d 1 -p $(pgrep -d',' java) -n 120 > log.txt 
  • The option -d allows to set the frequency used by top to refresh the data.
  • The option -b means that the traditional interface of top is not used. Instead, it sends everything to the standard output and then you can use a pipe (|) or a redirection (>).
  • The option -n informs about the number of iterations top should execute.

After that you can type:

cat log.txt | grep USER_OF_PROCESS 

You will see the execution time of the process and also %CPU, Memory and all that.

like image 21
Inti Gonzalez-Herrera Avatar answered Sep 28 '22 11:09

Inti Gonzalez-Herrera