@@ -48,23 +48,27 @@ class ResourceMonitor(threading.Thread):
48
48
to a file
49
49
"""
50
50
51
- def __init__ (self , pid , freq = 5 , fname = None , python = True ):
51
+ def __init__ (self , pid , freq = 0.2 , fname = None , cwd = None ):
52
52
# Make sure psutil is imported
53
53
import psutil
54
54
55
- if freq < 0.2 :
56
- raise RuntimeError ("Frequency (%0.2fs) cannot be lower than 0.2s" % freq )
55
+ # Leave process initialized and make first sample
56
+ self ._process = psutil .Process (pid )
57
+ _sample = self ._sample (cpu_interval = 0.2 )
57
58
58
- if fname is None :
59
- fname = ".proc-%d_time-%s_freq-%0.2f" % (pid , time (), freq )
60
- self ._fname = os .path .abspath (fname )
59
+ # Continue monitor configuration
60
+ freq = max (freq , 0.2 )
61
+ fname = fname or f".proc-{ pid } "
62
+ self ._fname = os .path .abspath (
63
+ os .path .join (cwd , fname ) if cwd is not None else fname
64
+ )
61
65
self ._logfile = open (self ._fname , "w" )
62
66
self ._freq = freq
63
67
self ._python = python
64
68
65
- # Leave process initialized and make first sample
66
- self . _process = psutil . Process ( pid )
67
- self ._sample ( cpu_interval = 0.2 )
69
+ # Dump first sample to file
70
+ print ( "," . join ( _sample ), file = self . _logfile )
71
+ self ._logfile . flush ( )
68
72
69
73
# Start thread
70
74
threading .Thread .__init__ (self )
@@ -80,7 +84,8 @@ def stop(self):
80
84
if not self ._event .is_set ():
81
85
self ._event .set ()
82
86
self .join ()
83
- self ._sample ()
87
+ # Dump last sample to file
88
+ print ("," .join (self ._sample ()), file = self ._logfile )
84
89
self ._logfile .flush ()
85
90
self ._logfile .close ()
86
91
@@ -132,15 +137,16 @@ def _sample(self, cpu_interval=None):
132
137
except psutil .NoSuchProcess :
133
138
pass
134
139
135
- print ("%f,%f,%f,%f" % (time (), cpu , rss / _MB , vms / _MB ), file = self ._logfile )
136
- self ._logfile .flush ()
140
+ return (time (), cpu , rss / _MB , vms / _MB )
137
141
138
142
def run (self ):
139
143
"""Core monitoring function, called by start()"""
140
144
start_time = time ()
141
145
wait_til = start_time
142
146
while not self ._event .is_set ():
143
- self ._sample ()
147
+ # Dump sample to file
148
+ print ("," .join (self ._sample ()), file = self ._logfile )
149
+ self ._logfile .flush ()
144
150
wait_til += self ._freq
145
151
self ._event .wait (max (0 , wait_til - time ()))
146
152
0 commit comments