Calculate rates from counter snapshots
Turn byte-counter deltas into full-duplex utilization while rejecting discontinuous evidence.
A counter is not a rate
An interface counter accumulates bytes over time. Subtract the earlier counter from the later one, multiply by eight to convert bytes to bits, and divide by elapsed seconds. The result is bits per second. Keep the calculation unrounded until display time.
Python integers preserve large counter values exactly. Converting a counter to floating point before subtraction can lose a small change when the total is very large. Subtract integer counters first, then divide the delta by the elapsed time.
Know when the calculation is unavailable
The export contains an epoch marker representing counter continuity. Both samples need the same nonempty marker. A changed marker, decreasing counter, invalid timestamp or nonpositive interval makes the rate unknown. This course does not guess whether a counter decrease was a reset or wrap.
The link is full duplex. Receive and transmit each have the declared speed available, so utilization is the larger directional rate divided by speed, not their sum. A computed direction over capacity indicates inconsistent evidence and also becomes unknown under this teaching policy.
Invalid speed is a policy error and raises ValueError. Invalid sample evidence returns an explicit unknown result with None measurements. No interface is polled; the script calculates from supplied snapshots.
before, after, seconds = 1000000, 2250000, 1
rx_bps = (after - before) * 8 / seconds
print(rx_bps, "bits per second")
Put it into practice.
Define interface_rate(previous, current, speed_bps). Speed must be finite positive int/float excluding bool, otherwise ValueError. Samples need equal nonempty string epoch, aware at timestamps with positive elapsed time, and nonnegative integer rx_bytes/tx_bytes excluding bool with no decrease. Bad/missing samples return {status:"unknown", rx_bps:None, tx_bps:None, utilization_percent:None}. Otherwise calculate integer deltas before division, convert bytes to bits/second, and use max(rx, tx)/speed*100 for full-duplex utilization. A value above 100% is unknown; exactly 100% is valid. Return status:"ok" with numeric unrounded measurements. Preserve inputs.
See an explained solution
from datetime import datetime, timezone
def parse_utc(value):
try:
moment = datetime.fromisoformat(value)
except (TypeError,ValueError) as error:
raise ValueError("Invalid timestamp") from error
if moment.tzinfo is None or moment.utcoffset() is None:
raise ValueError("Timestamp needs an offset")
return moment.astimezone(timezone.utc)
import math
def interface_rate(previous, current, speed_bps):
if type(speed_bps) not in (int,float) or not math.isfinite(speed_bps) or speed_bps <= 0:
raise ValueError("Speed must be a positive finite bit rate")
unknown = {"status":"unknown","rx_bps":None,"tx_bps":None,"utilization_percent":None}
if not isinstance(previous,dict) or not isinstance(current,dict):
return unknown
if not isinstance(previous.get("epoch"),str) or not previous["epoch"] or previous["epoch"] != current.get("epoch"):
return unknown
try:
seconds = (parse_utc(current.get("at"))-parse_utc(previous.get("at"))).total_seconds()
except ValueError:
return unknown
if seconds <= 0:
return unknown
deltas = []
for key in ("rx_bytes","tx_bytes"):
before, after = previous.get(key),current.get(key)
if type(before) is not int or type(after) is not int or before < 0 or after < before:
return unknown
deltas.append((after-before)*8/seconds)
utilization = max(deltas)/speed_bps*100
if utilization > 100:
return unknown
return {"status":"ok","rx_bps":deltas[0],"tx_bps":deltas[1],"utilization_percent":utilization}
if __name__ == "__main__":
print(interface_rate({"epoch":"one","at":"2026-11-17T12:00:00Z","rx_bytes":0,"tx_bytes":0}, {"epoch":"one","at":"2026-11-17T12:00:01Z","rx_bytes":1250000,"tx_bytes":250000}, 100000000))
The calculation preserves small changes in large counters and keeps discontinuities explicit. Its full-duplex rule avoids reporting ordinary simultaneous send/receive traffic as over capacity.