メモリとCPU使用率の計算

メモリとCPU使用率の計算

/proc/statファイルを使用して/proc/statusプロセスのCPUとメモリ使用率を計算する方法を知りたいです。ユーザーが使用する合計メモリとCPUを計算できますか?

ベストアンサー1

ps最も簡単な情報インターフェースです/proc

各ユーザーのメモリを一覧表示する1つの方法は次のとおりです。

$ ps -e -o uid,vsz | awk '
{ usage[$1] += $2 }
END { for (uid in usage) { print uid, ":", usage[uid] } }'

本当にprocを使用したい場合は、PythonやPerlなどを使用して一度繰り返して、/proc/*/statusユーザー/使用キー/値のペアをハッシュに保存することをお勧めします。

関連フィールドは/proc/PID/status次のとおりです。

Uid:    500     500     500     500
VmSize:     1234 kB

私の考えでは、この4つのUid番号は実際のuid、有効なuid、save uid、およびfs uidであると思います。

実際のuidが欲しいと仮定すると、次のように動作します。

# print uid and the total memory (including virtual memory) in use by that user
# TODO add error handling, e.g. not Linux, values not in kB, values not ints, etc.

import os
import sys
import glob

# uid=>vsz in KB
usermem = {}

# obtain information from Linux /proc file system
# http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html
os.chdir('/proc')
for file in glob.glob('[0-9]*'):
    with open(os.path.join(file, 'status')) as status:
        uid = None
        mem = None
        for line in status:
            if line.startswith('Uid:'):
                label, ruid, euid, suid, fsuid = line.split()
                uid = int(ruid)
            elif line.startswith('VmSize:'):
                label, value, units = line.split()
                mem = int(value)
        if uid and mem:
            if uid not in usermem:
                usermem[uid] = 0
            usermem[uid] += mem

for uid in usermem:
    print '%d:%d' % (uid,usermem[uid])

CPUはさらに難しいです。

ps(1) のマニュアルページには次のように表示されます。

   CPU usage is currently expressed as the percentage of time spent
   running during the entire lifetime of a process. This is not ideal,
   and it does not conform to the standards that ps otherwise conforms to.
   CPU usage is unlikely to add up to exactly 100%.

だからよくわかりません。たぶんtopそれがどのように処理されるのかを見ることができます。または、ps -e -o uid,pid,elapsed指定された間隔で2回実行して2回減算することもできます。

または、この目的に適したものをインストールしてください。プロセス会計

おすすめ記事