A measurement guide published on November 22, 2026, by Shattered lays out a 12-step, roughly 60-minute method for bridging that divide across Windows and Linux using a wall meter or smart plug, component sensors, and a zero-dependency Python 3.12 logging pipeline. Rather than relying on generic online wattage calculators, the workflow turns your own PC into a repeatable power lab covering idle, video playback, gaming, and rendering workloads. Because the supplied Python scripts were tested by their author only as a prototype against synthetic data, a local Shelly HTTP stub, and mocked command outputs—rather than physical GPUs or wall meters—think of the code as a solid reference framework to verify on your own hardware before treating any output as gospel.
Why Wall Power and Software Sensors Disagree
Every watt readout comes with a strict boundary, and confusing those boundaries is where most PC power estimates go sideways. Software tools only report what specific silicon or board sensors can see on the DC side of your power supply unit (PSU), whereas a wall meter measures everything on the AC side of the outlet.
| Measurement Source | What It Captures | What It Misses | Typical Tooling |
|---|---|---|---|
| Wall meter or smart plug | Total AC draw for everything on that outlet | Cannot split power by PC component | Plug-in LCD wattmeter, Shelly/Tapo smart plug |
| GPU power sensor | Graphics board power reported by the driver | CPU, motherboard, RAM, drives, fans, PSU losses | nvidia-smi, HWiNFO, Linux amdgpu hwmon |
| CPU package sensor | Processor package energy or power counter | Discrete GPU, chipset, RAM, VRMs, PSU losses | HWiNFO, Linux powercap (RAPL) |
| Online wattage calculator | Vendor-modeled component guesses | Real-world workloads, power plans, background tasks | Web-based PSU sizing tools |
Between the wall socket and your processor socket sits an AC-to-DC power supply whose conversion efficiency shifts depending on load, alongside motherboard VRMs, RAM sticks, NVMe drives, case fans, RGB controllers, and USB peripherals. Sensor tools and wall meters also carry their own reporting scopes and accuracy tolerances—nvidia-smi documentation, for example, notes an accuracy window of plus or minus 5 watts on supported board-power queries. Treating wall measurements and chip sensors as complementary boundaries—one for the household cost, the other for component attribution—keeps your math honest.
Software Prerequisites and Hardware Scope
Even on current late-2026 flagship silicon such as the NVIDIA GeForce RTX 5090, AMD Radeon RX 9070 XT, or AMD Ryzen 9 9950X3D, the underlying OS telemetry interfaces remain consistent with previous generations. To follow the full workflow, you need roughly an hour, a repeatable benchmark or workload, a recent utility bill, and the following software stack:
- Python 3.12 (tested on 3.12.3): Runs the logger using only the Python standard library, requiring no
pippackages. - HWiNFO v8.60: Released on November 10, 2026, this Windows diagnostic staple captures CPU and GPU sensors to CSV and recently added expanded NVIDIA power rail descriptions alongside updated Intel PresentMon support.
nvidia-smi: Ships alongside NVIDIA drivers on Windows and Linux for querying GPU board power.- Linux
powercap(RAPL) andamdgpuhwmon: Kernel-exposed interfaces for CPU package energy and Radeon board power on Linux desktops.
Steps 1 to 4: Defining Boundaries, Hardware, and Clean Baselines
Step 1: Pick the Question and Lock the Boundary
Before plugging anything in, decide what you actually want to learn, because your goal dictates your tools:
- What does this PC cost per month? You need AC wall watts across a representative schedule. Software sensors alone cannot capture full system or outlet draw.
- Which component is responsible? You need synchronized wall readings alongside GPU and CPU telemetry.
- Did an undervolt or setting change help? You need identical before-and-after workloads measured at the wall, because lowering GPU power can occasionally shift load—and watts—onto the CPU.
Just as critical is locking your physical boundary. If your monitor, speakers, and desk lamp share the meter, you are measuring the desk. If only the tower is plugged in, you are measuring the PC. Mixing those setups between runs invalidates every comparison, so write your boundary directly into your CSV filenames.
Step 2: Set Up the Project Workspace
Keep the scripts isolated in a dedicated powerlog directory. In Windows 11 PowerShell, initialize a virtual environment with Python 3.12:
mkdir powerlog; cd powerlog
py -3.12 -m venv.venv
.\.venv\Scripts\Activate.ps1
python --version
On Linux or macOS, use the standard venv module:
mkdir powerlog && cd powerlog
python3 -m venv.venv
source.venv/bin/activate
python3 --version
Confirm that both commands report Python 3.12.x. Save the main logger as powerlog.py, and if you run Windows, add hwinfo_to_powerlog.py alongside it.
Step 3: Choose a Safe Wall Meter or Smart Plug
Wall-side hardware generally falls into three camps: basic LCD plug-in wattmeters (cheap, manual readings), energy-monitoring smart plugs (ideal if they expose a local LAN API), and in-line Wi-Fi power modules. Shattered's guide cites examples such as the TP-Link Tapo P115 smart plug—rated by TP-Link for a maximum 15 A, 1,800 W general-use or resistive load at 100–125 V—alongside Kasa plugs and the Shelly PM Mini Gen3, an in-line module rated up to 16 A at 240 VAC that requires fixed electrical wiring rather than plugging into a wall socket.
Do not cut corners on electrical safety. Always follow the meter or smart plug's published electrical ratings and manufacturer instructions, verify that the device is certified for your region and load type, and hire a qualified electrician for any in-line or fixed-circuit installation. If you want automated CSV logging without cloud scraping, prioritize devices with documented local APIs—such as Shelly Gen2+ hardware over local HTTP, Tasmota-flashed plugs over HTTP/MQTT, or plugs supported by community local libraries—while remembering that not every smart plug exposes local polling without cloud dependencies.
Step 4: Capture a Clean Idle Baseline
Most desktops spend the majority of their powered-on hours idling, meaning a sloppy idle figure will skew your entire annual electricity projection. Reboot the system and wait 10 minutes before logging so Windows Update, search indexing, cloud-sync clients, and game-launcher shader compilation settle down. Close browsers and chat apps, leave the mouse untouched during the capture, and keep monitor brightness steady if the display shares your meter.
On Windows 11, record your exact power configuration before starting, because background defaults matter enormously. Run:
powercfg /getactivescheme
powercfg /getactiveoverlay
Windows 11 layers the Settings app's Power Mode overlay (such as Balanced or Best Performance) on top of the underlying Control Panel power scheme. Driver updates or vendor utilities can silently flip Power Mode without changing your base scheme, so logging both powercfg outputs ensures apples-to-apples comparisons. On Linux systems running power-profiles-daemon, run powerprofilesctl get and record the active profile. For laptops, measure only with the battery completely full or disconnected so charging currents do not pollute workload readings.
Steps 5 to 8: Reading Telemetry Across Windows, Linux, and Smart Plugs
Step 5: Query NVIDIA GPUs With nvidia-smi
Installed with NVIDIA's drivers on both Windows and Linux, nvidia-smi outputs board power cleanly in CSV format. Test your card directly from a terminal:
nvidia-smi --query-gpu=timestamp,name,power.draw,power.limit,utilization.gpu --format=csv -l 1
Modern drivers on Ampere (excluding GA100) and newer architectures also expose power.draw.average and power.draw.instant. Developer testing on Blackwell hardware shows that standard power.draw and power.draw.average generally reflect a smoothed rolling average updating roughly every 0.5 to 1 second, while power.draw.instant still avoids sub-second transient spikes unless you dip directly into NVML's sample buffer. For multi-minute energy accounting, power.draw works well, though some laptops, virtual machines, and specific Linux nvidia-open setups return [N/A]. The Python sampler handles [N/A] gracefully by leaving the cell blank rather than crashing or writing a misleading zero.
Step 6: Read AMD GPUs and CPU Counters on Linux
On Linux, the kernel's amdgpu driver exposes board or SoC power in microwatts under /sys/class/drm/card*/device/hwmon/hwmon*/. Checking /sys/class/drm/card[0-9]/device/vendor for AMD's 0x1002 vendor ID separates discrete Radeon cards from integrated graphics. Kernel documentation notes that drivers may expose power1_average, power1_input, or both, depending on the specific GPU or APU—and on AMD APUs, that reading includes CPU power as part of the combined SoC figure.
For CPU package energy on Linux, the powercap framework tracks cumulative microjoules in energy_uj files alongside max_energy_range_uj for counter wraparound—commonly located under /sys/class/powercap/intel-rapl:0/ on both Intel and kernel 5.8+ AMD Ryzen systems, though you should verify the exact path on your machine. Because of the PLATYPUS power side-channel vulnerability (CVE-2020-8694), Linux kernels since 5.10 restrict energy_uj to root access by default. You must either run the sampler with sudo or configure an explicit udev rule if you want non-root logging. Note also that because RAPL stores cumulative energy rather than instantaneous watts, the sampler primes the counter before the loop and calculates watts from the delta divided by elapsed seconds.
Step 7: Log Windows Sensors With HWiNFO v8.60
Windows lacks a native unprivileged user interface equivalent to Linux RAPL, and AMD Radeon cards on Windows lack an nvidia-smi CLI counterpart. HWiNFO v8.60 fills both gaps. Launch it in Sensors-only mode, click the logging icon at the bottom of the sensor window, save a CSV file, and run your workload.
Because HWiNFO column headers vary by motherboard and CPU architecture, inspect your power-related headers in PowerShell first:
$rows = Import-Csv.\hwinfo-gaming.CSV -Encoding Default
$rows[0].PSObject.Properties.Name | Select-String "Power"
If you run HWiNFO on a localized Windows install that writes decimal commas inside a comma-separated file, or if your motherboard labels CPU power differently, pass the exact column substrings using the adapter script's --gpu-col and --cpu-col flags. Note that Shattered's guide mentions forum reports of initialization crashes on at least one laptop under an early 8.60 build; while not independently corroborated in official release notes, keeping your previous HWiNFO installer handy is sensible troubleshooting insurance.
Step 8: Poll a Local Smart Plug Over HTTP
Shelly Gen2+ devices expose a local JSON-RPC 2.0 HTTP API on your LAN. After finding the plug's IP address on your router, test it in a terminal or browser:
curl -s "[url]http://192.168.1.50/rpc/Switch.GetStatus?id=0[/url]"
Relay-equipped plugs return active power in watts under the apower field, while meter-only Shelly components may use PM1.GetStatus?id=0. If curl returns a 404 error, you may have an older Gen1 Shelly device using /status or a different channel ID. For any non-Shelly meter—such as a Python wrapper around python-kasa—the sampler provides a --wall-cmd hook that runs an external command and parses the first whitespace-separated number it prints.
Steps 9 to 12: Sampling, Scenarios, Cost Math, and Comparisons
Step 9: Run the Sampler and Test Your Pipeline
The sampler polls all available sources at a fixed interval, compensates for network or subprocess read time so intervals stay steady, records blank cells instead of zeros when a sensor is missing, and flushes every row immediately to disk. Run a six-second dry test first:
python3 powerlog.py sample --out test.csv --scenario test --interval 1 --minutes 0.1
Inspect test.csv to verify that wall_w, gpu_w, and cpu_w populate as expected before committing to longer runs.
Step 10: Execute Four Repeatable Load Scenarios
Single-point wattage numbers tell you very little; grouping consistent workloads reveals where your electricity actually goes:
| Scenario | Recommended Workload | Suggested Duration | Variables to Lock Down |
|---|---|---|---|
idle | Clean desktop, nothing active | 5 min (after 10-min settle) | Power plan, Power Mode, display brightness, peripherals |
video | Fixed 1080p or 4K clip | 5 min | Media player, resolution, hardware decoding, volume |
gaming | Repeatable benchmark or replay | 10+ min (allow thermal settle) | In-game settings, resolution, frame-rate cap/VSync, room temp |
render | Fixed project export or compile | Until completion | Project file, encoder preset, target output |
Wait until the workload reaches steady state before starting the logger—especially in gaming, where GPU temperatures, fan curves, and leakage current stabilize after several minutes—and stop logging before returning to menus. At a two-second polling interval, a five-minute capture yields 150 rows.
Step 11: Convert Watts Into Kilowatt-Hours and Dollars
Cost calculation is simple energy arithmetic:
$$\text{kWh/day} = \frac{\sum (\text{mean_watts}{\text{scenario}} \times \text{hours/day}{\text{scenario}}) + \text{off_watts} \times \text{remaining_hours}}{1000}$$
Divide your most recent total utility bill by the total kilowatt-hours billed to get your effective rate—which folds in delivery fees, riders, and taxes that headline rates hide. If you are on a time-of-use tariff, split scenarios into peak and off-peak runs and calculate each band separately.
Running powerlog.py demo generates a purely synthetic dataset (demonstration values around 70 W idle, 85 W video, 430 W gaming, and 520 W render, where synthetic GPU and CPU sensors account for 77 percent of synthetic wall draw) solely to verify that the script executes cleanly. Do not mistake those synthetic outputs for real PC measurements. Likewise, if you lack a wall meter and pass --rest-w to estimate motherboard, RAM, drives, fans, and PSU overhead on top of HWiNFO or sensor logs, powerlog.py flags the output as an estimate. Treat that mode as a rough approximation with significant uncertainty, because an arbitrary constant cannot model nonlinear PSU efficiency curves.
Step 12: Measure Before and After a Tweak
Real insight happens when you change exactly one variable—an undervolt, a GPU power limit, a frame cap, or a Windows power plan—and re-run the identical scenario under the identical meter boundary. Name your output files descriptively (for example, after-uv-950mv.csv), then run powerlog.py compare to calculate per-scenario wattage shifts and projected annual kilowatt-hour savings. Pair those watt savings with PresentMon or benchmark frame rates so you can weigh frames per watt: dropping 25 watts at the cost of 1 percent performance is an easy win, whereas saving $6 a year at the expense of system stability or noticeable stutter rarely justifies the effort.
(Implementation note: In cmd_compare below, percentage change divides directly by the baseline wattage. If any scenario averages 0.0 W, Python will raise a ZeroDivisionError; guard against zero baselines if adapting the script for production use.)
Complete Prototype Scripts
powerlog.py
#!/usr/bin/env python3
"""powerlog: sample PC power sources into a CSV, then turn the CSV into kWh and cost."""
import argparse
import csv
import glob
import json
import random
import shlex
import shutil
import statistics
import subprocess
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from urllib.request import urlopen
FIELDS = ["ts", "scenario", "wall_w", "gpu_w", "cpu_w"]
def read_nvidia():
exe = shutil.which("nvidia-smi")
if not exe:
return None
try:
out = subprocess.run(
[exe, "--query-gpu=power.draw", "--format=csv,noheader,nounits"],
capture_output=True,
text=True,
timeout=5,
check=True,
).stdout
return sum(float(line) for line in out.strip().splitlines())
except (subprocess.SubprocessError, OSError, ValueError):
return None
def read_amdgpu():
for card in glob.glob("/sys/class/drm/card[0-9]"):
try:
if Path(card, "device/vendor").read_text().strip()!= "0x1002":
continue
except OSError:
continue
for name in ("power1_average", "power1_input"):
for path in glob.glob(f"{card}/device/hwmon/hwmon*/{name}"):
try:
return int(Path(path).read_text()) / 1e6
except (OSError, ValueError):
continue
return None
def read_gpu():
watts = read_nvidia()
return watts if watts is not None else read_amdgpu()
class Rapl:
"""CPU package power from the Linux powercap energy counter (usually needs root)."""
def __init__(self):
base = Path("/sys/class/powercap/intel-rapl:0")
self.counter = base / "energy_uj"
try:
self.wrap = int((base / "max_energy_range_uj").read_text())
except (OSError, ValueError):
self.wrap = 2**32
self.last = None
def watts(self):
try:
energy, now = int(self.counter.read_text()), time.monotonic()
except (OSError, ValueError):
return None
previous, self.last = self.last, (energy, now)
if previous is None or now <= previous[1]:
return None
delta = energy - previous[0]
if delta < 0:
delta += self.wrap
return delta / 1e6 / (now - previous[1])
def read_shelly(host):
for method in ("Switch.GetStatus?id=0", "PM1.GetStatus?id=0"):
try:
with urlopen(f"http://{host}/rpc/{method}", timeout=3) as resp:
data = json.load(resp)
if "apower" in data:
return float(data["apower"])
except (OSError, ValueError):
continue
return None
def read_wall_cmd(command):
try:
out = subprocess.run(
shlex.split(command), capture_output=True, text=True, timeout=10, check=True
).stdout
return float(out.strip().split()[0])
except (subprocess.SubprocessError, OSError, ValueError, IndexError):
return None
def fmt(value):
return "" if value is None else f"{value:.1f}"
def cmd_sample(args):
out = Path(args.out)
is_new = not out.exists()
rapl = Rapl()
rapl.watts() # prime the counter so the first row has a delta
stop = time.monotonic() + args.minutes * 60 if args.minutes else None
print(f"logging to {out} every {args.interval}s, scenario '{args.scenario}' (Ctrl+C to stop)")
with out.open("a", newline="") as fh:
writer = csv.DictWriter(fh, fieldnames=FIELDS)
if is_new:
writer.writeheader()
try:
while True:
started = time.monotonic()
wall = (
read_shelly(args.shelly)
if args.shelly
else read_wall_cmd(args.wall_cmd)
if args.wall_cmd
else None
)
row = {
"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"scenario": args.scenario,
"wall_w": fmt(wall),
"gpu_w": fmt(read_gpu()),
"cpu_w": fmt(rapl.watts()),
}
writer.writerow(row)
fh.flush()
if stop and time.monotonic() >= stop:
break
time.sleep(max(0.0, args.interval - (time.monotonic() - started)))
except KeyboardInterrupt:
print("stopped")
def load(paths):
rows = []
for path in paths:
with open(path, newline="") as fh:
rows.extend(csv.DictReader(fh))
return rows
def number(text):
try:
return float(text)
except (TypeError, ValueError):
return None
def estimate(row, rest_w):
wall = number(row.get("wall_w"))
if wall is not None:
return wall, "wall"
gpu, cpu = number(row.get("gpu_w")), number(row.get("cpu_w"))
if gpu is not None and cpu is not None:
return gpu + cpu + rest_w, "gpu+cpu+rest"
return None, None
def summarize(rows, rest_w):
groups = {}
for row in rows:
watts, source = estimate(row, rest_w)
if watts is None:
continue
groups.setdefault(row["scenario"], []).append((watts, source, row["ts"]))
stats = {}
for scenario, items in groups.items():
watts = [w for w, _, _ in items]
times = [datetime.fromisoformat(t) for _, _, t in items]
stats[scenario] = {
"n": len(watts),
"mean": statistics.fmean(watts),
"peak": max(watts),
"minutes": (max(times) - min(times)).total_seconds() / 60,
"source": "wall" if all(s == "wall" for _, s, _ in items) else "estimate",
}
return stats
def parse_profile(text):
profile = {}
for part in text.split(","):
name, _, hours = part.partition("=")
profile[name.strip()] = float(hours)
if sum(profile.values()) > 24:
sys.exit("profile hours add up to more than 24")
return profile
def energy_per_day(stats, profile, off_w):
missing = [name for name in profile if name not in stats]
if missing:
sys.exit(f"no samples for scenario(s): {', '.join(missing)}")
wh = sum(stats[name]["mean"] * hours for name, hours in profile.items())
return (wh + off_w * (24 - sum(profile.values()))) / 1000
def money(kwh_day, rate, symbol):
return {"day": kwh_day * rate, "month": kwh_day * 30 * rate, "year": kwh_day * 365 * rate, "symbol": symbol}
def cmd_report(args):
stats = summarize(load(args.csv), args.rest_w)
if not stats:
sys.exit("no usable rows: check that wall_w or gpu_w and cpu_w were logged")
print(f"{'scenario':<12}{'samples':>8}{'minutes':>9}{'mean W':>9}{'peak W':>9} source")
for name, s in sorted(stats.items()):
print(f"{name:<12}{s['n']:>8}{s['minutes']:>9.1f}{s['mean']:>9.1f}{s['peak']:>9.1f} {s['source']}")
if args.profile:
kwh = energy_per_day(stats, parse_profile(args.profile), args.off_w)
cost = money(kwh, args.rate, args.currency)
print(f"profile: {args.profile} rate: {args.currency}{args.rate}/kWh")
print(f"energy: {kwh:.3f} kWh/day, {kwh * 30:.1f} kWh/month, {kwh * 365:.0f} kWh/year")
print(f"cost: {args.currency}{cost['day']:.2f}/day, {args.currency}{cost['month']:.2f}/month, {args.currency}{cost['year']:.2f}/year")
shares = [
(number(r["gpu_w"]) + number(r["cpu_w"])) / number(r["wall_w"])
for r in load(args.csv)
if number(r.get("wall_w")) and number(r.get("gpu_w")) is not None and number(r.get("cpu_w")) is not None
]
if shares:
print(f"GPU+CPU sensors account for {statistics.fmean(shares) * 100:.0f}% of wall power on average")
def cmd_compare(args):
before = summarize(load([args.before]), args.rest_w)
after = summarize(load([args.after]), args.rest_w)
profile = parse_profile(args.profile)
print(f"{'scenario':<12}{'before W':>10}{'after W':>10}{'change':>9}")
for name in profile:
if name in before and name in after:
b, a = before[name]["mean"], after[name]["mean"]
print(f"{name:<12}{b:>10.1f}{a:>10.1f}{(a - b) / b * 100:>8.1f}%")
saved = energy_per_day(before, profile, args.off_w) - energy_per_day(after, profile, args.off_w)
print(f"saved: {saved * 365:.0f} kWh/year = {args.currency}{saved * 365 * args.rate:.2f}/year at {args.currency}{args.rate}/kWh")
def cmd_demo(args):
random.seed(7)
base = {"idle": 70, "video": 85, "gaming": 430, "render": 520}
start = datetime(2026, 11, 22, 18, 0, tzinfo=timezone.utc)
scale = 0.93 if args.undervolt else 1.0
with open(args.out, "w", newline="") as fh:
writer = csv.DictWriter(fh, fieldnames=FIELDS)
writer.writeheader()
for index, (scenario, watts) in enumerate(base.items()):
for i in range(150):
wall = watts * scale + random.gauss(0, watts * 0.03)
writer.writerow(
{
"ts": (start + timedelta(minutes=10 * index, seconds=2 * i)).isoformat(timespec="seconds"),
"scenario": scenario,
"wall_w": fmt(wall),
"gpu_w": fmt(wall * 0.55),
"cpu_w": fmt(wall * 0.22),
}
)
print(f"wrote synthetic demo data to {args.out}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("sample", help="log power readings to CSV")
s.add_argument("--out", default="power.csv")
s.add_argument("--scenario", required=True)
s.add_argument("--interval", type=float, default=2.0)
s.add_argument("--minutes", type=float, default=0, help="stop after N minutes (0 = until Ctrl+C)")
s.add_argument("--shelly", help="IP of a Shelly plug with energy monitoring")
s.add_argument("--wall-cmd", help="command that prints wall watts as its first token")
s.set_defaults(func=cmd_sample)
def common(p):
p.add_argument("--profile", help="hours per day, e.g. idle=12,video=2,gaming=3,render=1")
p.add_argument("--rate", type=float, default=0.15, help="price per kWh (example default, use your bill)")
p.add_argument("--currency", default="$")
p.add_argument("--off-w", type=float, default=0.0, help="watts while off or asleep")
p.add_argument("--rest-w", type=float, default=0.0, help="guess for board, RAM, fans and drives when no wall meter")
r = sub.add_parser("report", help="summarise CSV logs")
r.add_argument("csv", nargs="+")
common(r)
r.set_defaults(func=cmd_report)
c = sub.add_parser("compare", help="before/after comparison")
c.add_argument("before")
c.add_argument("after")
common(c)
c.set_defaults(func=cmd_compare)
d = sub.add_parser("demo", help="write synthetic sample data")
d.add_argument("--out", default="demo.csv")
d.add_argument("--undervolt", action="store_true", help="shift the synthetic watts down 7%")
d.set_defaults(func=cmd_demo)
args = parser.parse_args()
if args.cmd == "compare" and not args.profile:
parser.error("compare needs --profile")
args.func(args)
if __name__ == "__main__":
main()
hwinfo_to_powerlog.py (Windows HWiNFO Adapter)
#!/usr/bin/env python3
"""Convert a HWiNFO sensor CSV log into powerlog's CSV format."""
import argparse
import csv
from datetime import datetime, timedelta, timezone
def find(header, needle):
for index, name in enumerate(header):
if needle.lower() in name.lower():
return index
raise SystemExit(f"no column containing '{needle}'. Columns: {header}")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("src")
ap.add_argument("dst")
ap.add_argument("--scenario", required=True)
ap.add_argument("--interval", type=float, default=2.0, help="HWiNFO polling interval in seconds")
ap.add_argument("--gpu-col", default="GPU Power")
ap.add_argument("--cpu-col", default="CPU Package Power")
args = ap.parse_args()
with open(args.src, newline="", encoding="cp1252", errors="replace") as fh:
reader = csv.reader(fh)
header = next(reader)
gpu_i, cpu_i = find(header, args.gpu_col), find(header, args.cpu_col)
start = datetime.now(timezone.utc).replace(microsecond=0)
with open(args.dst, "a", newline="") as out:
writer = csv.writer(out)
if out.tell() == 0:
writer.writerow(["ts", "scenario", "wall_w", "gpu_w", "cpu_w"])
count = 0
for row in reader:
try:
gpu = float(row[gpu_i].replace(",", "."))
cpu = float(row[cpu_i].replace(",", "."))
except (ValueError, IndexError):
continue
ts = start + timedelta(seconds=args.interval * count)
writer.writerow([ts.isoformat(timespec="seconds"), args.scenario, "", f"{gpu:.1f}", f"{cpu:.1f}"])
count += 1
print(f"converted {count} rows from {args.src}")
if __name__ == "__main__":
main()
Quick Pitfalls and Troubleshooting Checklist
- Missing
cpu_won Linux: Confirm/sys/class/powercap/intel-rapl:0exists and run withsudoor an explicitudevpermission rule. Remember that the initial priming read is intentionally discarded. - Blank
gpu_wvalues: Checknvidia-smiPATH availability on Windows, verify/sys/class/drm/card*/device/vendorreads0x1002on Linux Radeon systems, or use HWiNFO if your GPU reports[N/A]. - Smart plug timeouts or 404s: Verify the plug's LAN IP in a browser first and ensure your router is not isolating Wi-Fi clients on a guest subnet.
- Driver updates shifting baselines: Always re-capture a clean baseline after major graphics driver or BIOS updates—Shattered notes, for instance, that AMD's 26.11.1 release notes flagged a Windows 10 Smart Access Memory regression that could alter power and performance simultaneously.
- Scenario name mismatches: Scenario strings in
--profileare case-sensitive;Gamingandgamingwill not match.
Measuring your own PC takes an hour of discipline, but it replaces PSU-calculator guesswork with hard numbers tailored to your exact hardware, Windows power settings, and utility bill. If you test this pipeline on your own Windows 11 or Linux rig—or pair it with PresentMon frame-time logs—share your real-world wall-versus-sensor findings in the WindowsForum.com hardware and overclocking threads.
References
- Measure PC Power Draw: 12 Steps, 60 Min - shattered.io shattered.io · 2026-11-22T16:28:29+00:00
- Power Capping Framework — The Linux Kernel documentation docs.kernel.org
- intel.com intel.com