Skip to content

Instantly share code, notes, and snippets.

@ag88
Last active May 6, 2024 07:48
Show Gist options
  • Save ag88/4724902c206bd03b7ec1005e0ee2c285 to your computer and use it in GitHub Desktop.
Save ag88/4724902c206bd03b7ec1005e0ee2c285 to your computer and use it in GitHub Desktop.
Linux check cpu hog processes
#!/usr/bin/env python3
#
# requires psutil (pip3 install psutil)
#
# This script runs ps_util.cpu_percent(interval=0.5) for each process to calc
# the cpu utilization percentage
# It does so concurrently as otherwise each calls sleeps 0.5 secs to sample the data
# to run it faster use more threads in ThreadPoolExecutor(max_worker=x or
# reduce the interval for cpu_percent(interval=x
# To make readings more 'accurate' use a longer interval e.g. 1.0 for 1s.
# many processes are short lived and this script may not 'catch' it while it runs.
#
# output is filtered, only processes where utilization > 0.001 is printed
# comment that if ut > 0.001 to print all processes
#
import concurrent.futures
import psutil
def pspct(pid):
try:
p = psutil.Process(pid)
ut = p.cpu_percent(interval=0.5)
return (pid, p.name(), ut)
except psutil.NoSuchProcess:
return None
pids = psutil.pids()
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
futures = {executor.submit(pspct, pid): pid for pid in pids}
for future in concurrent.futures.as_completed(futures):
try:
data = future.result()
if not data is None:
(pid, name, ut) = data
if ut > 0.001:
print(pid, name, ut)
except Exception as exc:
print('thread exception {}'.format(exc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment