Ubuntu – How to log memory and cpu usage of an application

command linecpu loadloggingmemory usage

Similar to question How to log CPU load?, I would like to log memory of a process.

The process I want to log, is killed on a remote server, and I want to find out the CPU load and the memory usage just before it was killed.

[update]

Both Stefano Palazzo's neat little python script and

MichaƂ's one line output values that are smaller than in top for CPU and Mem. Do you have an idea why?

output top:

 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND 
2312 schXX     20   0 1241m 328m  58m S  100  0.3  11:56.68 MATLAB 

output Stefano Palazzo's python script:

python memlogger.py 2312
%CPU    %MEM
76.00   0.20
76.00   0.20

Best Answer

You can create one-liner in shell:

logpid() { while sleep 1; do  ps -p $1 -o pcpu= -o pmem= ; done; }

to log process with pid=123 just:

logpid 123

or to see and write log to file:

logpid $$ | tee /tmp/pid.log

If you want other data to be logged, modify -o {this} options. See man ps section "STANDARD FORMAT SPECIFIERS" for available parameters to use. If you want different time resolution, change sleep {this} in function logpid().