Skip to content

Instantly share code, notes, and snippets.

@wimglenn
Created November 2, 2017 18:05
Show Gist options
  • Save wimglenn/3186645d0474550160d3210bf488f8f8 to your computer and use it in GitHub Desktop.
Save wimglenn/3186645d0474550160d3210bf488f8f8 to your computer and use it in GitHub Desktop.
Human readable data rates
class Speed:
"""
For human-readable bitrates
>>> now = datetime.utcnow()
>>> then = now - timedelta(seconds=4)
>>> speed = Speed(n_bytes=200e6, start_time=then, end_time=now) # e.g. transferring approx 200 meg in 4 seconds
>>> print(speed)
50000000.0 bytes/s
>>> f'{speed:MBps}' # specify units in the format mini language
'47.6837158203125 MBps'
>>> f'{speed:Gbps}'
'0.4 Gbps'
>>> f'{speed:8,kBps}' # the segment before the unit gets passed up to default formatter
'48,828.125 kBps'
"""
divisors = {
'kbps': 1_000 / 8,
'Mbps': 1_000_000 / 8,
'Gbps': 1_000_000_000 / 8,
'kBps': 1_024,
'MBps': 1_048_576,
'GBps': 1_073_741_824,
}
def __init__(self, n_bytes, start_time, end_time):
try:
self.bytes_per_second = n_bytes / (end_time-start_time).total_seconds()
except ZeroDivisionError:
self.bytes_per_second = float('inf')
def __str__(self):
return format(self)
def __format__(self, format_spec):
if format_spec.endswith(tuple(self.divisors)):
format_spec, units = format_spec[:-4], format_spec[-4:]
divisor = self.divisors[units]
else:
divisor = 1
units = 'bytes/s'
return f'{self.bytes_per_second/divisor:{format_spec}} {units}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment