サイズ表示を読みやすくする
30分プログラム、その447。サイズ表示を読みやすくする。
clmemo@aka: Linux でプロセスごとのメモリー使用量を調べるによると、psにlオプションを与えてやると各プロセスのメモリ使用量を表示してくれるらしい。
# RSSの列 UID PID PPID CPU PRI NI VSZ RSS WCHAN STAT TT TIME COMMAND 0 1 0 0 31 0 76512 480 - Ss ?? 0:00.45 /sbin/launchd 0 10 1 0 31 0 75944 412 - Ss ?? 0:01.99 /usr/libexec/kextd
でもKB単位でしか表示してくれないから、読みづらい。というわけで、GとかMとかをつけて、読みやすくするプログラムを書いてみよう。
使い方
$ echo 1230 | python human-readable.py 1.23M
あとはRSSの列にこれを適用するプログラムをawkあたりで書いてやる。
#!/usr/bin/awk -f BEGIN{ FS=" +" } { "echo " $9 "| python human-readable.py" | getline size printf " %-8s %s\n",size,$14 }
試しにemacsのメモリ使用量でも調べている。
$ ps axl | grep emacs | memsize
13.37M emacs
ソースコード
#! /usr/bin/python # -*- mode:python; coding:utf-8 -*- # # human-readable.py - # # Copyright(C) 2008 by mzp # Author: MIZUNO Hiroki / mzpppp at gmail dot com # http://howdyworld.org # # Timestamp: 2008/12/28 22:15:33 # # This program is free software; you can redistribute it and/or # modify it under MIT Lincence. # import sys Unit = [('G',10**6),('M',10**3),('K',1)] def human_readable(n): f = float(n) for (unit,size) in Unit: g = f / size if g > 1.0: return '%.2f%s' % (g,unit) return '%.2f' % f for line in sys.stdin: try: print human_readable(int(line)) except ValueError: print line