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

前端 未结 21 1938
抹茶落季
抹茶落季 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)

提交回复
热议问题