Created
February 15, 2024 05:23
-
-
Save NIXKnight/511e8ba2cb8e36cf4e6dc4527d12e114 to your computer and use it in GitHub Desktop.
Get a list of top memory consumers on a Linux system
This file contains 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 sys | |
import psutil | |
from tabulate import tabulate | |
def get_top_memory_processes(n=10): | |
# Fetch all processes | |
processes = [p.info for p in psutil.process_iter(attrs=['pid', 'name', 'memory_percent', 'memory_info'])] | |
# Sort the processes based on memory percentage used | |
processes.sort(key=lambda x: x['memory_percent'], reverse=True) | |
# Prepare the data for tabulation | |
data = [] | |
for proc in processes[:n]: | |
pid = proc['pid'] | |
name = proc['name'] | |
mem_percent = f"{proc['memory_percent']:.2f}%" | |
mem_usage_mb = f"{proc['memory_info'].rss / 1024 / 1024:.2f} MB" | |
data.append([pid, name, mem_percent, mem_usage_mb]) | |
# Tabulate and print the data | |
print(tabulate(data, headers=['PID', 'COMMAND', '%MEM', 'MEM(MB)'], tablefmt='grid')) | |
if __name__ == "__main__": | |
# Default to 10 processes if no argument is given | |
n = 10 | |
if len(sys.argv) > 1: | |
try: | |
n = int(sys.argv[1]) | |
except ValueError: | |
print("Please enter a valid integer for the number of processes.") | |
sys.exit(1) | |
get_top_memory_processes(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment