Skip to content

Instantly share code, notes, and snippets.

@hidva
Last active August 27, 2016 05:11
Show Gist options
  • Save hidva/f17169ccc569ec766b4e9a6369fa947d to your computer and use it in GitHub Desktop.
Save hidva/f17169ccc569ec766b4e9a6369fa947d to your computer and use it in GitHub Desktop.
周期性对指定进程的 /proc/pid/statm 文件进行采样.
#! /usr/bin/python
#coding:utf-8
import time
import sys
import getopt
import os
def PrintHelpAndExit() :
print "Usage: %s -f path -p pid -t time" % (sys.argv[0])
print "-t time; 单位为秒, 但可以为浮点数, 来实现更高精度."
sys.exit(1)
opts, non_opts = getopt.getopt(sys.argv[1:], "f:p:t:")
output_filepath = ""
pid = ""
sleep_time = 0.1 # 秒
for opt, arg in opts :
if opt == "-f" :
output_filepath = arg
elif opt == "-p" :
pid = arg
elif opt == "-t" :
sleep_time = float(arg)
if sleep_time == 0 or len(output_filepath) == 0 or len(pid) == 0 :
PrintHelpAndExit()
input_filepath = "/proc/" + pid + "/statm"
output_file = open(output_filepath, "ab", 0)
while True :
with open(input_filepath, "rb") as input :
info = input.next()
output_file.write(", ".join(info.split()) + "\n")
time.sleep(sleep_time);
@hidva
Copy link
Author

hidva commented Aug 27, 2016

$ ./sample_statm.py -f test.out -p 1 -t 0.01
^CTraceback (most recent call last):
  File "./sample_statm.py", line 39, in <module>
    time.sleep(sleep_time);
KeyboardInterrupt
$ wc -l test.out 
511 test.out
$ head -n 33 test.out 
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0
2664, 8, 0, 9, 0, 81, 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment