Retrieve CPU usage and memory usage of a single process on Linux?

前端 未结 21 1839
抹茶落季
抹茶落季 2020-11-27 09:00

I want to get the CPU and memory usage of a single process on Linux - I know the PID. Hopefully, I can get it every second and write it to a CSV using the \'watch\' command

相关标签:
21条回答
  • 2020-11-27 09:33

    ps command (should not use):

    • CPU usage is currently expressed as the percentage of time spent running during the entire lifetime of a process.

    top command (should use):

    • The task's share of the elapsed CPU time since the last screen update, expressed as a percentage of total CPU time.

    Use top to get CPU usage in real time(current short interval):

    top -b -n 2 -d 0.2 -p 6962 | tail -1 | awk '{print $9}'

    will echo like: 78.6

    • -b: Batch-mode
    • -n 2: Number-of-iterations, use 2 because: When you first run it, it has no previous sample to compare to, so these initial values are the percentages since boot.
    • -d 0.2: Delay-time(in second, here is 200ms)
    • -p 6962: Monitor-PIDs
    • tail -1: the last row
    • awk '{print $9}': the 9-th column(the cpu usage number)
    0 讨论(0)
  • 2020-11-27 09:35

    As commented in caf's answer above, ps and in some cases pidstat will give you the lifetime average of the pCPU. To get more accurate results use top. If you need to run top once you can run:

    top -b -n 1 -p <PID>
    

    or for process only data and header:

    top -b -n 1 -p <PID> | tail -3 | head -2
    

    without headers:

    top -b -n 1 -p <PID> | tail -2 | head -1
    
    0 讨论(0)
  • 2020-11-27 09:36

    This is a nice trick to follow one or more programs in real time while also watching some other tool's output: watch "top -bn1 -p$(pidof foo),$(pidof bar); tool"

    0 讨论(0)
  • 2020-11-27 09:38

    Use pidstat (from sysstat - Refer Link).

    e.g. to monitor these two process IDs (12345 and 11223) every 5 seconds use

    $ pidstat -h -r -u -v -p 12345,11223 5
    
    0 讨论(0)
  • 2020-11-27 09:39
    ps aux|awk  '{print $2,$3,$4}'|grep PID
    

    where the first column is the PID,second column CPU usage ,third column memory usage.

    0 讨论(0)
  • 2020-11-27 09:40

    Launch a program and monitor it

    This form is useful if you want to benchmark an executable easily:

    topp() (
      $* &>/dev/null &
      pid="$!"
      trap ':' INT
      echo 'CPU  MEM'
      while sleep 1; do ps --no-headers -o '%cpu,%mem' -p "$pid"; done
      kill "$pid"
    )
    topp ./myprog arg1 arg2
    

    Now when you hit Ctrl + C it exits the program and stops monitoring. Sample output:

    CPU  MEM
    20.0  1.3
    35.0  1.3
    40.0  1.3
    

    Related: https://unix.stackexchange.com/questions/554/how-to-monitor-cpu-memory-usage-of-a-single-process

    Tested on Ubuntu 16.04.

    0 讨论(0)
提交回复
热议问题