-
Notifications
You must be signed in to change notification settings - Fork 22
/
monitor_memory.py
executable file
·153 lines (124 loc) · 5.01 KB
/
monitor_memory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python3
#
# Copyright (c) 2012 Realz Slaw, 2017 Gao Wang
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import time
import psutil
import subprocess
class ProcessTimer:
def __init__(self, command, interval = 1):
self.command = command
self.execution_state = False
self.interval = interval
def execute(self):
self.max_vms_memory = 0
self.max_rss_memory = 0
self.t0 = time.time()
self.t1 = None
self.max_t = [self.t0]
try:
self.p = subprocess.Popen(self.command, shell=False)
except FileNotFoundError:
self.p = None
sys.exit("Invalid command `{}`".format(sys.argv[1]))
self.execution_state = True
def poll(self):
if not self.check_execution_state():
return False
self.t1 = time.time()
try:
pp = psutil.Process(self.p.pid)
# Obtain a list of the subprocess and all its descendants.
descendants = list(pp.children(recursive=True))
descendants = descendants + [pp]
rss_memory = 0
vms_memory = 0
# Calculate and sum up the memory of the subprocess and all its
# descendants.
for descendant in descendants:
try:
mem_info = descendant.memory_info()
rss_memory += mem_info[0]
vms_memory += mem_info[1]
except (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied):
# Sometimes a subprocess descendant will have terminated
# between the time we obtain a list of descendants, and the
# time we actually poll this descendant's memory usage.
pass
if int(self.max_vms_memory * 1E-8) < int(vms_memory * 1E-8):
# Peak memory updated, at ~100-MB resolution.
self.max_t = [self.t1]
if int(self.max_vms_memory * 1E-8) == int(vms_memory * 1E-8):
# Peak memory maintained.
self.max_t = [self.max_t[0], self.t1]
self.max_vms_memory = max(self.max_vms_memory,vms_memory)
self.max_rss_memory = max(self.max_rss_memory,rss_memory)
except (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied):
return self.check_execution_state()
return self.check_execution_state()
def is_running(self):
return psutil.pid_exists(self.p.pid) and self.p.poll() == None
def check_execution_state(self):
if not self.execution_state:
return False
if self.is_running():
return True
self.executation_state = False
self.t1 = time.time()
return False
def close(self,kill=False):
if self.p is not None:
try:
pp = psutil.Process(self.p.pid)
if kill:
pp.kill()
else:
pp.terminate()
except (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied):
pass
def takewhile_excluding(iterable, value = ['|', '<', '>']):
for it in iterable:
if it in value:
return
yield it
if __name__ == '__main__':
import sys, os
if len(sys.argv) <= 1:
sys.exit()
interval = float(os.environ['MEM_CHECK_INTERVAL']) if 'MEM_CHECK_INTERVAL' in os.environ else 1
ptimer = ProcessTimer(takewhile_excluding(sys.argv[1:]), interval)
try:
ptimer.execute()
# Poll as often as possible; otherwise the subprocess might
# "sneak" in some extra memory usage while you aren't looking.
while ptimer.poll():
time.sleep(ptimer.interval)
finally:
# Make sure that we don't leave the process dangling.
ptimer.close()
sys.stderr.write('\ntime elapsed: {:.2f}s\n'.format(max(0, ptimer.t1 - ptimer.t0 - ptimer.interval * 0.5)))
sys.stderr.write('peak first occurred: {:.2f}s\n'.format(min(ptimer.max_t) - ptimer.t0))
sys.stderr.write('peak last occurred: {:.2f}s\n'.format(max(ptimer.max_t) - ptimer.t0))
sys.stderr.write('max vms_memory: {:.2f}GB\n'.format(ptimer.max_vms_memory * 1.07E-9))
sys.stderr.write('max rss_memory: {:.2f}GB\n'.format(ptimer.max_rss_memory * 1.07E-9))
sys.stderr.write('memory check interval: %ss\n' % ptimer.interval)
sys.stderr.write('return code: %s\n' % ptimer.p.returncode)