Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


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:

2312 schXX     20   0 1241m 328m  58m S  100  0.3  11:56.68 MATLAB 

output Stefano Palazzo's python script:

python 2312
%CPU    %MEM
76.00   0.20
76.00   0.20
share|improve this question

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().

share|improve this answer

This simple python script should do what you want:

import time
import string
import sys
import commands

def get_cpumem(pid):
    d = [i for i in commands.getoutput("ps aux").split("\n")
        if i.split()[1] == str(pid)]
    return (float(d[0].split()[2]), float(d[0].split()[3])) if d else None

if __name__ == '__main__':
    if not len(sys.argv) == 2 or not all(i in string.digits for i in sys.argv[1]):
        print("usage: %s PID" % sys.argv[0])
        while True:
            x = get_cpumem(sys.argv[1])
            if not x:
                print("no such process")
            print("%.2f\t%.2f" % x)
    except KeyboardInterrupt:

You first need to find out the process id of the program you want to monitor, then you can run the script with the PID as an argument:

python 3912

It will print the cpu usage and ram usage in per cent two times a second:

%CPU    %MEM
0.90    0.40
1.43    0.40
8.21    0.40

You can then redirect its output to a file in order to import it into a spreadsheet later (python 9391 > firefox_log.txt) and import the data into a spreadsheet selecting Tab as your separator.

The program quits when you hit Ctrl+C or when the process is killed.

share|improve this answer
Dear Stefano, thank you very much for your script. Unfortunately it seems to output wrong results. Do you have any idea why? Please see my updated question. – Framester Aug 8 '11 at 12:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.