Skip to content

Instantly share code, notes, and snippets.

@Lukasa Lukasa/README.md
Created Sep 26, 2016

Embed
What would you like to do?
Benchmark for python-hyper/hpack#62.

To run this benchmark, clone this gist, cd into the directory, and then run tox. This will print a set of results.

from __future__ import print_function
import platform
import sys
import timeit
is_py2 = (sys.version_info[0] == 2)
if is_py2:
def to_byte(char):
return ord(char)
else:
def to_byte(char):
return char
def decode_integer_old(data, prefix_bits):
max_number = (2 ** prefix_bits) - 1
mask = 0xFF >> (8 - prefix_bits)
index = 0
number = to_byte(data[index]) & mask
if number == max_number:
while True:
index += 1
next_byte = to_byte(data[index])
if next_byte >= 128:
number += (next_byte - 128) * (128 ** (index - 1))
else:
number += next_byte * (128 ** (index - 1))
break
return number, index + 1
def decode_integer_new(data, prefix_bits):
max_number = (2 ** prefix_bits) - 1
mask = 0xFF >> (8 - prefix_bits)
index = 0
shift = 0
number = to_byte(data[index]) & mask
if number == max_number:
while True:
index += 1
next_byte = to_byte(data[index])
if next_byte >= 128:
number += (next_byte - 128) << shift
else:
number += next_byte << shift
break
shift += 7
return number, index + 1
inputs = (
(b'\x0f\xf1\xff\x3f', 4),
(b'\x1f\xe1\xff\x3f', 5),
(b'\x3f\xc1\xff\x3f', 6),
(b'\x7f\x81\xff\x3f', 7),
)
if __name__ == '__main__':
for data, prefix_bits in inputs:
for func in ("decode_integer_old", "decode_integer_new"):
print("{} {} {} (prefix bits {:d})".format(
platform.python_implementation(),
platform.python_version(),
func,
prefix_bits,
))
timer = timeit.Timer(
stmt="{}({!r}, {:d})".format(func, data, prefix_bits),
setup="from main import {}".format(func)
)
results = timer.repeat()
print(results)
[tox]
envlist = py27, py33, py34, py35, pypy
skipsdist= True
[testenv]
commands= python main.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.