MCPcopy
hub / github.com/saltstack/salt / top

Function top

salt/modules/ps.py:102–167  ·  view source on GitHub ↗

Return a list of top CPU consuming processes during the interval. num_processes = return the top N CPU consuming processes interval = the number of seconds to sample CPU usage over CLI Examples: .. code-block:: bash salt '*' ps.top salt '*' ps.top 5 10

(num_processes=5, interval=3)

Source from the content-addressed store, hash-verified

100
101
102def top(num_processes=5, interval=3):
103 """
104 Return a list of top CPU consuming processes during the interval.
105 num_processes = return the top N CPU consuming processes
106 interval = the number of seconds to sample CPU usage over
107
108 CLI Examples:
109
110 .. code-block:: bash
111
112 salt '*' ps.top
113
114 salt '*' ps.top 5 10
115 """
116 result = []
117 start_usage = {}
118 for pid in psutil.pids():
119 try:
120 process = psutil.Process(pid)
121 except psutil.NoSuchProcess:
122 continue
123 else:
124 try:
125 user, system = process.cpu_times()[:2]
126 except psutil.ZombieProcess:
127 user = system = 0.0
128 start_usage[process] = user + system
129 time.sleep(interval)
130 usage = set()
131 for process, start in start_usage.items():
132 try:
133 user, system = process.cpu_times()[:2]
134 except psutil.NoSuchProcess:
135 continue
136 now = user + system
137 diff = now - start
138 usage.add((diff, process))
139
140 for diff, process in sorted(usage, key=lambda x: x[0], reverse=True):
141 info = {
142 "cmd": _get_proc_cmdline(process) or _get_proc_name(process),
143 "user": _get_proc_username(process),
144 "status": _get_proc_status(process),
145 "pid": _get_proc_pid(process),
146 "create_time": _get_proc_create_time(process),
147 "cpu": {},
148 "mem": {},
149 }
150 try:
151 for key, value in process.cpu_times()._asdict().items():
152 info["cpu"][key] = value
153 for key, value in process.memory_info()._asdict().items():
154 info["mem"][key] = value
155 except psutil.NoSuchProcess:
156 # Process ended since psutil.pids() was run earlier in this
157 # function. Ignore this process and do not include this process in
158 # the return data.
159 continue

Callers

nothing calls this directly

Calls 13

_get_proc_cmdlineFunction · 0.85
_get_proc_usernameFunction · 0.85
_get_proc_statusFunction · 0.85
_get_proc_create_timeFunction · 0.85
ProcessMethod · 0.80
cpu_timesMethod · 0.80
setFunction · 0.70
_get_proc_nameFunction · 0.70
_get_proc_pidFunction · 0.70
sleepMethod · 0.45
itemsMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected