若是使用過glances
,若是有一顆geek的心的話,必定會以爲不但酷炫並且十分實用。不過若是想觀察一個程序從運行開始到結束的cpu佔用率怎麼辦?好辦,利用python的psutil
異步觀察就行。python
介紹一下放在github上的一個項目: oscillolinux
使用方式很簡單,直接 pip install oscillo
便可安裝使用.git
命令行參數的格式是 "<name>: <command [args]>"
:github
name
: 命令行的別名/id (任意字符串),當--commands/-c
參數指定多個命令時,該值將做爲命令的惟一標識,不可重複command [args]
: 須要測試資源消耗的命令,好比 gzip file.ext
示例以下,監控gzip壓縮一個文件時耗費的cpu、memory和時間:shell
oscillo -c 'gzip: gzip file.ext' -o output-file
命令執行完成後,會在當前目錄下生成一個<output-file>.log
文件。文本結構是json 格式. 數據結構以下json
{ "test": { "elapsed": 0.022143125534057617, //總執行時間 "cpu": [], "memory": [] } }
同時會產生一個<output-file>.png
文件,<output-file>
由-o
參數指定,默認值爲metrix
數據結構
在控制檯上,oscillo
會打印summary信息,其中包含命令的耗時、最大內存使用、最大cpu使用、退出碼等在控制檯上,oscillo
會打印summary信息,其中包含命令的耗時、最大內存使用、最大cpu使用、退出碼等app
若是想對比多個命令對資源的消耗,可使用 -c/--commands
選項指定多條命令, e.g.:異步
對比gzip
和tar
命令對資源的消耗:工具
oscillo -c 't1: gzip file.ext' 't2: tar czf target.tar.gz file1' -o output
效果以下:
這個工具的原型,來自於一次爲了對比幾種客戶端性能而寫的一個腳本,它的原理就是:
psutil
觀察該進程,每隔一段時間記錄一次cpu和內存的負載matplotlib
畫圖說一下其中碰到的一個坑:欲監控的子進程A在內部調用了另外一個耗資源的子進程B,可是psutil只能觀察到子進程A的資源消耗狀況,粗暴的解決辦法就是:觀察全局的資源消耗狀況:
class Stopwatch(object): def __init__(self, pid): self.__is_run = False self.__start_time = 0 self.__elapsed_times = 0 self.memory_percent = [] self.cpu_percent = [] self.pid = pid def start(self): if self.__is_run: return False self.__is_run = True self.__start_time = time.time() if self.pid > 0: p = psutil.Process(self.pid) else: p = psutil p.memory_percent = lambda: p.virtual_memory().percent while self.__is_run: try: self.cpu_percent.append(p.cpu_percent(1)) self.memory_percent.append(p.memory_percent()) except psutil.NoSuchProcess: break @property def elapsed(self): if self.__is_run: return self.__elapsed_times + time.time() - self.__start_time return self.__elapsed_times def stop(self): self.__elapsed_times = self.elapsed self.__is_run = False
當前的功能比較簡單,可能有不少東西沒用想到,歡迎使用和完善
git倉庫: oscillo