特定のプロセスが突然暴走したり、メモリ使用量が変化していたりする際に使うのがpsであったり、topなどになります。しかしこれらはリアルタイムの状態を表示しており、常に関している訳にはいきません。 そこで使ってみたいのがpsrecordです。特定のプロセスのCPU、メモリ変化をログにしてくれます。

psrecordの使い方

psrecordはプロセス番号を指定して実行します。

$ psrecord 55566 --log activity.txt
Attaching to process 55566

そうするとログにCPU、メモリ使用量を記録してくれます。測定するインターバルなどはオプションで指定できます。

$ cat activity.txt
# Elapsed time   CPU (%)     Real (MB)   Virtual (MB)
       0.000        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430
       0.001        0.000       25.766     4264.430

ヘルプです。

$ psrecord -h
usage: psrecord [-h] [--log LOG] [--plot PLOT] [--duration DURATION]
                [--interval INTERVAL] [--include-children]
                process_id_or_command

Record CPU and memory usage for a process

positional arguments:
  process_id_or_command
                        the process id or command

optional arguments:
  -h, --help            show this help message and exit
  --log LOG             output the statistics to a file
  --plot PLOT           output the statistics to a plot
  --duration DURATION   how long to record for (in seconds). If not specified,
                        the recording is continuous until the job exits.
  --interval INTERVAL   how long to wait between each sample (in seconds). By
                        default the process is sampled as often as possible.
  --include-children    include sub-processes in statistics (results in a
                        slower maximum sampling rate).

psrecordを使うことでプロセスの変化を可視化できます。ファイルの他、plot向けに出力できるのでグラフ化することもできるでしょう。常にログし続けるのは難しいと思うので、再現性の高い処理の解析などで便利そうです。

psrecordはPython製のオープンソース・ソフトウェア(2-clause BSD lisence)です。

astrofrog/psrecord: Record the CPU and memory activity of a process