Skip to content

Instantly share code, notes, and snippets.

@romuald
Created February 16, 2025 15:12
Show Gist options
  • Select an option

  • Save romuald/7aeba5f40693bb351da4abe62ad7321d to your computer and use it in GitHub Desktop.

Select an option

Save romuald/7aeba5f40693bb351da4abe62ad7321d to your computer and use it in GitHub Desktop.
Timing of b85encode
"""
Testing of run time of b85encode method
"""
import timeit
import random
import signal
from time import time
from functools import partial
from base64 import b85encode
class AlarmTimer:
runtime: int
count: int
target = callable
def __init__(self, runtime: int, target):
self.runtime = int(runtime)
if self.runtime < 1:
raise ValueError('wait_time must be at least 1 second')
self.target = target
self.count = 0
def run(self):
run_flag = [1]
def stop_callback(*_):
run_flag[:] = []
signal.signal(signal.SIGALRM, signal.SIG_DFL)
signal.signal(signal.SIGALRM, stop_callback)
signal.alarm(self.runtime)
count = 0
target = self.target
while run_flag:
target()
count += 1
# Discard the last call from count
self.count = count - 1
@property
def average(self):
return self.runtime / self.count
@staticmethod
def time_format(seconds: float, precision: int = 2):
ns = seconds * 1e9
fmt = f"0.{precision}f"
if ns < 1:
return f"{ns * 1e3:{fmt}} ps"
if ns < 1e3:
return f"{ns:{fmt}} ns"
if ns < 1e6:
return f"{ns / 1e3:{fmt}} µs"
if ns < 1e9:
return f"{ns / 1e6:{fmt}} ms"
return f"{ns / 1e9:{fmt}} s"
RUN_TIME = 2.0
SMALL_INPUT: bytes = b"hello world"
MEDIUM_INPUT: bytes
BIG_INPUT: bytes
VERYBIG_INPUT: bytes
def init():
global MEDIUM_INPUT, BIG_INPUT, VERYBIG_INPUT
rnd = random.Random()
rnd.seed(42)
MEDIUM_INPUT = rnd.randbytes(200)
BIG_INPUT = rnd.randbytes(5_000)
VERYBIG_INPUT = rnd.randbytes(500_000)
def main():
init()
for name in "SMALL", "MEDIUM", "BIG", "VERYBIG":
ref = globals()[f"{name}_INPUT"]
aa = AlarmTimer(RUN_TIME, partial(b85encode, ref))
aa.run()
avg = aa.average
bl = len(ref)
per_call = aa.time_format(avg)
per_byte = aa.time_format(avg / bl)
print(f"{name} ({bl} bytes): {aa.count} iterations ({per_call} per call, {per_byte} per byte)")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment