Created
May 21, 2025 11:44
-
-
Save vanschelven/2a25fd388e23ac756a843a194c56c8aa to your computer and use it in GitHub Desktop.
CPU on Fire? Douse the Tab
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import subprocess | |
| from time import sleep | |
| from datetime import datetime | |
| COL_PID = 0 | |
| COL_CPU = 8 | |
| COL_NAME = 11 | |
| FF_CPU_THRESHOLD = 50 | |
| TIME_THRESHOLD = 10 | |
| bad_counts = 0 | |
| worst_web_components = {} # pid -> total CPU usage in the time firefox was misbehaving | |
| while True: | |
| sleep(1) | |
| sp = subprocess.run('top -b -n1 -o +%CPU'.split(" "), capture_output=True) | |
| lines = sp.stdout.splitlines()[7:] # skip the first 7 lines of header | |
| # first we check total firefox CPU usage | |
| total_cpu = 0 | |
| for line in lines: | |
| line = line.decode("utf-8") | |
| columns = line.split(maxsplit=11) | |
| ps_name = columns[COL_NAME] | |
| if 'firefox' not in ps_name and 'Isolate' not in ps_name and 'RDD Pro' not in ps_name: | |
| continue | |
| cpu = float(columns[COL_CPU]) | |
| total_cpu += cpu | |
| if total_cpu > FF_CPU_THRESHOLD: | |
| bad_counts += 1 | |
| else: | |
| print(f"{datetime.now().strftime('%H:%M:%S')} Reset at {total_cpu} CPU usage") | |
| bad_counts = 0 | |
| if bad_counts == 0: | |
| # no bad firefox processes; we reset the "worst" list and skip the rest | |
| worst_web_components = {} | |
| continue | |
| for line in lines: | |
| line = line.decode("utf-8") | |
| columns = line.split(maxsplit=11) | |
| ps_name = columns[COL_NAME] | |
| if 'Isolate' not in ps_name and 'RDD Pro' not in ps_name: | |
| continue | |
| pid = int(columns[COL_PID]) | |
| cpu = float(columns[COL_CPU]) | |
| if pid not in worst_web_components: | |
| worst_web_components[pid] = 0 | |
| worst_web_components[pid] += cpu | |
| if bad_counts >= TIME_THRESHOLD: | |
| print(f"{datetime.now().strftime('%H:%M:%S')} A FF-related proces was seen {bad_counts} times over the CPU threshold.") | |
| worst = sorted(worst_web_components.items(), key=lambda x: x[1], reverse=True)[0] | |
| worst_pid, worst_cpu = worst | |
| print(f"{datetime.now().strftime('%H:%M:%S')} PID {worst_pid} is worst Isolated Web Component") | |
| subprocess.run(f"kill {worst_pid}".split(" ")) | |
| # Reset the counters | |
| bad_counts = 0 | |
| worst_web_components = {} | |
| else: | |
| print(f"{datetime.now().strftime('%H:%M:%S')} Firefox was bad {bad_counts} times, but not enough to kill anything.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment