Skip to content

Instantly share code, notes, and snippets.

@lynzrand
Created April 30, 2024 02:46
Show Gist options
  • Save lynzrand/4444010cc3c98413e3c2a380f0fec89b to your computer and use it in GitHub Desktop.
Save lynzrand/4444010cc3c98413e3c2a380f0fec89b to your computer and use it in GitHub Desktop.
Accumulated memory usage checker (generated by GPT)
import psutil
import matplotlib.pyplot as plt
def get_running_processes():
running_processes = []
# Iterate over all running processes
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
try:
process_info = proc.info
pid = process_info['pid']
name = process_info['name']
memory_info = process_info['memory_info']
memory_usage = memory_info.rss # Get the RSS (Resident Set Size) in bytes
running_processes.append((pid, name, memory_usage))
except (psutil.NoSuchProcess, psutil.AccessDenied):
# Handle exceptions for processes that are no longer available or inaccessible
pass
# Sort processes based on memory usage (ascending order)
running_processes.sort(key=lambda x: x[2]) # Sort by memory usage (ascending order)
return running_processes
def main():
processes = get_running_processes()
if processes:
process_names = []
memory_usages = []
accumulated_memory_usages = []
accumulated_memory = 0
print("List of running processes (sorted by memory usage, ascending):")
for index, (pid, name, memory_usage) in enumerate(processes):
# Convert memory usage to MB for easier readability
memory_mb = memory_usage / (1024 * 1024) # Convert bytes to MB
# Calculate accumulated memory usage of processes with smaller memory footprints
accumulated_memory += memory_mb
process_names.append(name)
memory_usages.append(memory_mb)
accumulated_memory_usages.append(accumulated_memory)
print(f"PID: {pid} | Name: {name} | Memory Usage: {memory_mb:.2f} MB | Accumulated Memory Usage: {accumulated_memory:.2f} MB")
# Plotting the graph
plt.figure(figsize=(12, 8))
# Plot memory usage as vertical bars
plt.bar(process_names, memory_usages, color='blue', label='Memory Usage (MB)')
# Plot accumulated memory usage as a line
plt.plot(process_names, accumulated_memory_usages, color='orange', marker='o', linestyle='-', linewidth=2, label='Accumulated Memory Usage (MB)')
plt.xlabel('Process')
plt.ylabel('Memory Usage (MB)')
plt.title('Memory Usage of Running Processes (Sorted by Memory Usage, Ascending)')
plt.xticks(rotation=90) # Rotate x-axis labels for better readability
plt.legend()
plt.tight_layout()
plt.show()
# Total memory usage of all processes combined
total_memory_usage = sum(memory_usages)
print(f"\nTotal Memory Usage of all processes: {total_memory_usage:.2f} MB")
else:
print("No processes are currently running.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment