Skip to content

Commit 962672a

Browse files
author
shorti1996
committed
cpu_percentage
process_sensor: clean process list each X update ticks
1 parent b1a4c5a commit 962672a

2 files changed

Lines changed: 20 additions & 6 deletions

File tree

ptop/plugins/process_sensor.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313

1414

1515
class ProcessSensor(Plugin):
16-
def __init__(self,**kwargs):
16+
PROCESS_LIST_CLEANUP_TICKS = 100
17+
18+
def __init__(self, **kwargs):
1719
super(ProcessSensor,self).__init__(**kwargs)
1820
# there will be two parts of the returned value, one will be text and other graph
1921
# there can be many text (key,value) pairs to display corresponding to each key
@@ -23,7 +25,8 @@ def __init__(self,**kwargs):
2325
self._currentSystemUser = getpass.getuser()
2426
self._logger = logging.getLogger(__name__)
2527
# processes once retrieved from psutil are stored in a list to make cpu percentage measurement possible
26-
self._process_list = []
28+
self._process_list = {}
29+
self._tick = 0
2730

2831
def format_time(self, d):
2932
ret = '{0} day{1} '.format(d.days, ' s'[d.days > 1]) if d.days else ''
@@ -94,11 +97,19 @@ def update(self):
9497
self.currentValue['text']['running_processes'] = str(proc_count)
9598
self.currentValue['text']['running_threads'] = str(thread_count)
9699

100+
self.tick(proc_info_list)
101+
102+
def tick(self, proc_info_list):
103+
self._tick = (self._tick + 1) % ProcessSensor.PROCESS_LIST_CLEANUP_TICKS
104+
if self._tick == 0:
105+
self._process_list = {key: value for (key, value) in self._process_list.items() if key in [y['id'] for y in proc_info_list]}
106+
97107
def retrieve_process_by_pid(self, pid):
98-
found_processes = [x for x in self._process_list if x.pid == pid]
99-
process = found_processes[0] if len(found_processes) > 0 else psutil.Process(pid)
100-
if not found_processes and process:
101-
self._process_list.append(process)
108+
try:
109+
process = self._process_list[pid]
110+
except KeyError:
111+
process = psutil.Process(pid)
112+
self._process_list[pid] = process
102113
return process
103114

104115

start.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from ptop import main
2+
3+
main.main()

0 commit comments

Comments
 (0)