I was interested to learn about the performance of various methods for a single whole in the range [0, 255] , so I decided to conduct some temporary tests.
Based on the time below and the general trend that I observed when I tried many different values ββand configurations, struct.pack seems to be the fastest, followed by int.to_bytes , bytes , and str.encode (which is not surprising) is the slowest. Note that the results show slightly more variations than presented, and int.to_bytes and bytes sometimes switch the speed ranking during testing, but struct.pack clearly the fastest.
Results in CPython 3.7 for Windows:
Testing with 63: bytes_: 100000 loops, best of 5: 3.3 usec per loop to_bytes: 100000 loops, best of 5: 2.72 usec per loop struct_pack: 100000 loops, best of 5: 2.32 usec per loop chr_encode: 50000 loops, best of 5: 3.66 usec per loop
Test module (named int_to_byte.py ):
"""Functions for converting a single int to a bytes object with that int value.""" import random import shlex import struct import timeit def bytes_(i): """From Tim Pietzcker answer: https://stackoverflow.com/a/21017834/8117067 """ return bytes([i]) def to_bytes(i): """From brunsgaard answer: https://stackoverflow.com/a/30375198/8117067 """ return i.to_bytes(1, byteorder='big') def struct_pack(i): """From Andy Hayden answer: https://stackoverflow.com/a/26920966/8117067 """ return struct.pack('B', i)
Graham Jan 03 '19 at 18:37 2019-01-03 18:37
source share