Created
December 12, 2022 10:07
-
-
Save BramVanroy/7f19bec7c7b97326ec9eed0723cdb28d to your computer and use it in GitHub Desktop.
Print out CPU/GPU memory usage (basic)
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 math | |
import psutil | |
from pynvml import nvmlDeviceGetCount, nvmlInit, nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo | |
def format_bytes(nbytes: int) -> str: | |
if nbytes == 0: | |
return "0 B" | |
unit = ("B", "kB", "MB", "GB", "TB") | |
nunit = int(math.floor(math.log(nbytes, 1024))) | |
nsize = round(nbytes/(math.pow(1024, nunit)), 2) | |
return f"{nsize:.2f} {unit[nunit]}" | |
def print_used_ram(): | |
ram = psutil.virtual_memory() | |
print("CPU used memory:", format_bytes(ram[3])) | |
print("CPU used memory (%):", f"{ram[3]*100/ram[0]:.2f}%") | |
def print_used_vram(): | |
nvmlInit() | |
if nvmlDeviceGetCount() < 1: | |
return None | |
h = nvmlDeviceGetHandleByIndex(0) | |
info = nvmlDeviceGetMemoryInfo(h) | |
print(f"GPU used memory:", format_bytes(info.used)) | |
print(f"GPU used memory (%):", f"{info.used*100/info.total:.2f}%") | |
if __name__ == "__main__": | |
print_used_ram() | |
print_used_vram() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment