| | |
| | """ |
| | Monitor GPU stats and output as a formatted table. |
| | """ |
| |
|
| | import subprocess |
| | import time |
| | import argparse |
| | from datetime import datetime |
| |
|
| |
|
| | def get_gpu_stats(): |
| | """Query GPU stats using nvidia-smi.""" |
| | cmd = [ |
| | "nvidia-smi", |
| | "--query-gpu=utilization.gpu,utilization.memory,memory.used,memory.total", |
| | "--format=csv,noheader,nounits" |
| | ] |
| | result = subprocess.run(cmd, capture_output=True, text=True) |
| | if result.returncode != 0: |
| | return None |
| |
|
| | values = result.stdout.strip().split(", ") |
| | if len(values) != 4: |
| | return None |
| |
|
| | return { |
| | "gpu_util": int(values[0]), |
| | "mem_util": int(values[1]), |
| | "mem_used": int(values[2]), |
| | "mem_total": int(values[3]) |
| | } |
| |
|
| |
|
| | def print_header(): |
| | """Print table header.""" |
| | print("+" + "-" * 25 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 18 + "+" + "-" * 18 + "+") |
| | print(f"| {'Timestamp':<23} | {'GPU %':>10} | {'Mem %':>10} | {'Used (MiB)':>16} | {'Total (MiB)':>16} |") |
| | print("+" + "-" * 25 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 18 + "+" + "-" * 18 + "+") |
| |
|
| |
|
| | def print_row(stats): |
| | """Print a table row.""" |
| | timestamp = datetime.now().strftime("%Y/%m/%d %H:%M:%S.%f")[:-3] |
| | print(f"| {timestamp:<23} | {stats['gpu_util']:>10} | {stats['mem_util']:>10} | {stats['mem_used']:>16} | {stats['mem_total']:>16} |") |
| |
|
| |
|
| | def print_footer(): |
| | """Print table footer.""" |
| | print("+" + "-" * 25 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 18 + "+" + "-" * 18 + "+") |
| |
|
| |
|
| | def main(): |
| | parser = argparse.ArgumentParser(description="Monitor GPU stats as a formatted table") |
| | parser.add_argument("-i", "--interval", type=float, default=2.0, help="Sampling interval in seconds (default: 2.0)") |
| | parser.add_argument("-n", "--count", type=int, default=0, help="Number of samples (0 = infinite)") |
| | args = parser.parse_args() |
| |
|
| | print_header() |
| |
|
| | count = 0 |
| | try: |
| | while args.count == 0 or count < args.count: |
| | stats = get_gpu_stats() |
| | if stats: |
| | print_row(stats) |
| | else: |
| | print("| ERROR: Could not get GPU stats" + " " * 47 + "|") |
| |
|
| | count += 1 |
| | if args.count == 0 or count < args.count: |
| | time.sleep(args.interval) |
| | except KeyboardInterrupt: |
| | pass |
| |
|
| | print_footer() |
| |
|
| |
|
| | if __name__ == "__main__": |
| | main() |
| |
|