File size: 2,402 Bytes
73132c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
"""
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()