Files
HealthAppRepository/tools/energy-jmeter/energy.py
T

28 lines
1.6 KiB
Python

#!/usr/bin/env python3
"""Integrate timestamped external power readings over the exact measurement window."""
import argparse, csv, datetime as dt, json
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('run');p.add_argument('power_csv');p.add_argument('--idle-watts',type=float);a=p.parse_args()
run=json.loads(Path(a.run).read_text());start=run['measurement_start_ms']/1000;end=run['measurement_end_ms']/1000
points=[]
with open(a.power_csv) as f:
for r in csv.DictReader(f):
instant=dt.datetime.fromisoformat(r['timestamp'].replace('Z','+00:00'))
if instant.tzinfo is None: p.error('Power timestamps require a timezone')
watts=float(r['power_watts'])
if not 0<=watts<float('inf'):p.error('Power must be finite and nonnegative')
points.append((instant.timestamp(),watts))
if len(points)<2 or any(b[0]<=a[0] for a,b in zip(points,points[1:])):p.error('Power timestamps must be strictly increasing')
if points[0][0]>start or points[-1][0]<end:p.error('Power samples must cover the entire measurement interval')
joules=0
for (t0,p0),(t1,p1) in zip(points,points[1:]):
lo=max(t0,start);hi=min(t1,end)
if hi<=lo:continue
plo=p0+(p1-p0)*(lo-t0)/(t1-t0);phi=p0+(p1-p0)*(hi-t0)/(t1-t0)
joules+=(plo+phi)/2*(hi-lo)
result={'duration_seconds':end-start,'joules':joules,'kWh':joules/3600000,'average_watts':joules/(end-start)}
if a.idle_watts is not None:result['joules_above_idle']=joules-a.idle_watts*(end-start)
count=run.get('measured_http_samples',0)
if count:result['joules_per_http_request']=joules/count
print(json.dumps(result,indent=2))