Make cpu_load_percent segment threaded

interval=0.5 means that it will block for 0.5 seconds which is bad. With 
             threading it blocks only the separate thread, and it does not hold 
             GIL (uses regular time.sleep to wait) in this case which is fine.
interval=0.05 means that it will report almost random value.
interval=None means that (assuming psutil.cpu_percent is called only by this 
              segment) it will report CPU load percent measured between two 
              subsequent .cpu_load_percent calls or cpu_load_percent call and 
              module import. It is used for update method to get immediate 
              result in case update_first is True.
This commit is contained in:
ZyX 2013-04-07 18:52:49 +04:00
parent 2685f61e88
commit f3ce370566

@ -558,16 +558,30 @@ try:
def _get_user(segment_info):
return psutil.Process(os.getpid()).username
def cpu_load_percent(pl, measure_interval=.5):
'''Return the average CPU load as a percentage.
class CPULoadPercentSegment(ThreadedSegment):
interval = 1
Requires the ``psutil`` module.
def update(self, old_cpu):
return psutil.cpu_percent(interval=None)
:param float measure_interval:
interval used to measure CPU load (in seconds)
'''
cpu_percent = int(psutil.cpu_percent(interval=measure_interval))
return '{0}%'.format(cpu_percent)
def run(self):
while not self.shutdown_event.is_set():
try:
self.update_value = psutil.cpu_percent(interval=self.interval)
except Exception as e:
self.exception('Exception while calculating cpu_percent: {0}', str(e))
def render(self, cpu_percent, format='{0:.0f}%', **kwargs):
return format.format(cpu_percent)
cpu_load_percent = with_docstring(CPULoadPercentSegment(),
'''Return the average CPU load as a percentage.
Requires the ``psutil`` module.
:param str format:
Output format. Accepts measured CPU load as the first argument.
''')
except ImportError:
def _get_bytes(interface): # NOQA
with open('/sys/class/net/{interface}/statistics/rx_bytes'.format(interface=interface), 'rb') as file_obj: