# cont 6-A: SM/mem clock ramp from a cold process under a sustained memory-bound load; NVML every 100 ms.
import time, torch, pynvml
pynvml.nvmlInit(); h = pynvml.nvmlDeviceGetHandleByIndex(0)
def rd(): return (pynvml.nvmlDeviceGetPerformanceState(h), pynvml.nvmlDeviceGetClockInfo(h, 1), pynvml.nvmlDeviceGetClockInfo(h, 2), pynvml.nvmlDeviceGetPowerUsage(h)//1000)
print("pre-context", rd(), "max sm/mem", pynvml.nvmlDeviceGetMaxClockInfo(h,1), pynvml.nvmlDeviceGetMaxClockInfo(h,2), "app", pynvml.nvmlDeviceGetApplicationsClock(h,1), flush=True)
buf = torch.empty(64 << 20, dtype=torch.float32, device="cuda:0"); torch.cuda.synchronize()
t0 = time.monotonic(); last = -1; prev = None
ev = [torch.cuda.Event(enable_timing=True) for _ in range(2)]
while time.monotonic() - t0 < 12:
    ev[0].record()
    for _ in range(8): buf.add_(1.0)
    ev[1].record(); ev[1].synchronize()
    if time.monotonic() - last >= 0.1:
        last = time.monotonic(); r = rd(); ms = ev[0].elapsed_time(ev[1])
        if r[:3] != prev: print(f"{last-t0:6.2f}s P{r[0]} sm {r[1]} mem {r[2]} {r[3]} W  8x256MB add {ms:.3f} ms", flush=True); prev = r[:3]
print(f"end {time.monotonic()-t0:.2f}s", rd(), f"{ms:.3f} ms", flush=True)
