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

前端 未结 21 1843
抹茶落季
抹茶落季 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:40

    For those who struggled for a while wonderring why the selected answer does not work:

    ps -p <pid> -o %cpu,%mem
    

    No SPACE ibetween %cpu, and %mem.

    0 讨论(0)
  • 2020-11-27 09:40
    ps axo pid,etime,%cpu,%mem,cmd | grep 'processname' | grep -v grep
    

    PID - Process ID

    etime - Process Running/Live Duration

    %cpu - CPU usage

    %mem - Memory usage

    cmd - Command

    Replace processname with whatever process you want to track, mysql nginx php-fpm etc ...

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

    CPU and memory usage of a single process on Linux or you can get the top 10 cpu utilized processes by using below command

    ps -aux --sort -pcpu | head -n 11

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

    You could use top -b and grep out the pid you want (with the -b flag top runs in batch mode), or also use the -p flag and specify the pid without using grep.

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

    Based on @caf's answer, this working nicely for me.

    Calculate average for given PID:

    measure.sh

    times=100
    total=0
    for i in $(seq 1 $times)
    do
       OUTPUT=$(top -b -n 1 -d 0.1 -p $1 | tail -1 | awk '{print $9}')
       echo -n "$i time: ${OUTPUT}"\\r
       total=`echo "$total + $OUTPUT" | bc -l`
    done
    #echo "Average: $total / $times" | bc
    
    average=`echo "scale=2; $total / $times" | bc`
    echo "Average: $average"
    

    Usage:

    # send PID as argument
    sh measure.sh 3282
    
    0 讨论(0)
  • 2020-11-27 09:48
    ps -p <pid> -o %cpu,%mem,cmd
    

    (You can leave off "cmd" but that might be helpful in debugging).

    Note that this gives average CPU usage of the process over the time it has been running.

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