Skip to content

Commit

Permalink
Merge pull request #58 from timmyb824/feat/include-psutil-mem
Browse files Browse the repository at this point in the history
feat: include mem usage from psutil
  • Loading branch information
timmyb824 authored May 10, 2024
2 parents e373c3d + 1394e4c commit 7410dfb
Showing 1 changed file with 32 additions and 21 deletions.
53 changes: 32 additions & 21 deletions src/core/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from typing import Literal, Optional
from tabulate import tabulate
import psutil

from src.utilities.utils import print_title

Expand Down Expand Up @@ -39,7 +40,7 @@ def format_memory_value(value_in_mb: float) -> str:


def get_memory_info() -> (
tuple[str, str, float | Literal[0], str, str, float | Literal[0]]
tuple[str, str, float | Literal[0], float | Literal[0], str, str, float | Literal[0], float | Literal[0]]
):
"""Get memory information"""
if platform.system() == "Darwin":
Expand All @@ -52,34 +53,38 @@ def get_memory_info() -> (
}
except (FileNotFoundError, PermissionError):
# print(f"Error reading file '/proc/meminfo': {exception}")
return ("0MB", "0MB", 0, "0MB", "0MB", 0)
return ("0MB", "0MB", 0, 0, "0MB", "0MB", 0, 0)

keys = ["MemTotal", "MemFree", "Buffers", "Cached", "SwapTotal", "SwapFree"]
if any(key not in mem_info for key in keys):
print("Not all keys found in '/proc/meminfo'")
return ("0MB", "0MB", 0, "0MB", "0MB", 0)
return ("0MB", "0MB", 0, 0, "0MB", "0MB", 0, 0)

total_memory, mem_free, mem_used_percentage = calculate_memory_usage(
total_memory, mem_free, mem_used_percentage_calc = calculate_memory_usage(
mem_info["MemTotal"],
mem_info["MemFree"],
mem_info["Buffers"],
mem_info["Cached"],
)

swap_total, swap_free, swap_used_percentage = calculate_memory_usage(
memory_usage = psutil.virtual_memory().percent
swap_usage = psutil.swap_memory().percent
swap_total, swap_free, swap_used_percentage_calc = calculate_memory_usage(
mem_info["SwapTotal"], mem_info["SwapFree"], 0, 0
)

return (
format_memory_value(total_memory),
format_memory_value(mem_free),
mem_used_percentage,
memory_usage,
mem_used_percentage_calc,
format_memory_value(swap_total),
format_memory_value(swap_free),
swap_used_percentage,
swap_usage,
swap_used_percentage_calc,
)
else:
return ("0MB", "0MB", 0, "0MB", "0MB", 0)
return ("0MB", "0MB", 0, 0, "0MB", "0MB", 0, 0)


def get_total_memory_of_all_processes() -> float:
Expand Down Expand Up @@ -112,19 +117,20 @@ def get_total_memory_of_all_processes() -> float:


def get_memory_info_macos() -> (
tuple[str, str, float | Literal[0], str, str, float | Literal[0]]
tuple[str, str, float | Literal[0], float | Literal[0], str, str, float | Literal[0], float | Literal[0]]
):
"""Get memory information on macOS"""
try:
sysctl_output = subprocess.check_output(["sysctl", "-n", "hw.memsize"]).decode()
except (subprocess.CalledProcessError, PermissionError):
return ("0MB", "0MB", 0, "0MB", "0MB", 0)
return ("0MB", "0MB", 0, 0, "0MB", "0MB", 0, 0)

total_memory = int(sysctl_output.strip()) // (1024 * 1024) # Convert bytes to MB

mem_usage_process = get_total_memory_of_all_processes()
mem_free = round(total_memory - mem_usage_process)
mem_used_percentage = (
memory_usage = psutil.virtual_memory().percent
mem_used_percentage_calc = (
((total_memory - mem_free) / total_memory) * 100 if total_memory != 0 else 0
)

Expand All @@ -135,17 +141,20 @@ def get_memory_info_macos() -> (
}
swap_total = swap_stats.get("total", 0) # Already in MB
swap_free = swap_stats.get("free", 0) # Already in MB
swap_used_percentage = (
swap_usage = psutil.swap_memory().percent
swap_used_percentage_calc = (
((swap_total - swap_free) / swap_total) * 100 if swap_total != 0 else 0
)

return (
format_memory_value(total_memory),
format_memory_value(mem_free),
mem_used_percentage,
memory_usage,
mem_used_percentage_calc,
format_memory_value(swap_total),
format_memory_value(swap_free),
swap_used_percentage,
swap_usage,
swap_used_percentage_calc,
)


Expand All @@ -154,8 +163,8 @@ def show_warning_msg() -> Optional[str]:
Print the macOS warning message
"""
if platform.system() == "Darwin":
return "\033[1mWARNING\033[0m: memory usage of all processes used to calculate free memory"
return "\033[1mWARNING\033[0m: memory usage derived from '/proc/meminfo'"
return "\033[1mWARNING\033[0m: calc memory usage derived from process info; sys usage from psutil"
return "\033[1mWARNING\033[0m: memory usage derived from '/proc/meminfo' and psutil"


def print_memory_info() -> None:
Expand All @@ -166,18 +175,20 @@ def print_memory_info() -> None:
(
mem_total,
mem_free,
mem_used_percentage,
memory_usage,
mem_used_percentage_calc,
swap_total,
swap_free,
swap_used_percentage,
swap_usage,
swap_used_percentage_calc,
) = get_memory_info()

table = [
["Memory", f"{mem_free}", f"{mem_total}", f"{mem_used_percentage:.2f}%"],
["Swap", f"{swap_free}", f"{swap_total}", f"{swap_used_percentage:.2f}%"],
["Memory", f"{mem_free}", f"{mem_total}", f"{mem_used_percentage_calc:.2f}%", f"{memory_usage:.2f}%"],
["Swap", f"{swap_free}", f"{swap_total}", f"{swap_used_percentage_calc:.2f}%", f"{swap_usage:.2f}%"],
]

headers = ["Type", "Free", "Total", "Usage"]
headers = ["Type", "Free", "Total", "Calc Usage", "Sys Usage"]

print_title("Memory Information")
print(show_warning_msg())
Expand Down

0 comments on commit 7410dfb

Please sign in to comment.