我对在范围[0, 255]
内的单个整数的各种方法的性能很感兴趣,因此我决定进行一些计时测试。
根据以下的计时结果和我从尝试许多不同的值和配置中观察到的一般趋势,struct.pack
似乎是最快的,其次是int.to_bytes
,bytes
,而str.encode
(毫不奇怪)是最慢的。请注意,结果显示了比所表示的更多的变化,int.to_bytes
和bytes
有时在测试期间会交换速度排名,但struct.pack
显然是最快的。
在Windows上的CPython 3.7中的结果:
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
测试模块(命名为int_to_byte.py
):
"""Functions for converting a single int to a bytes object with that int's value."""
import random
import shlex
import struct
import timeit
def bytes_(i):
"""From Tim Pietzcker's answer:
https://dev59.com/SWEi5IYBdhLWcg3wueN0#21017834
"""
return bytes([i])
def to_bytes(i):
"""From brunsgaard's answer:
https://dev59.com/SWEi5IYBdhLWcg3wueN0#30375198
"""
return i.to_bytes(1, byteorder='big')
def struct_pack(i):
"""From Andy Hayden's answer:
https://dev59.com/SWEi5IYBdhLWcg3wueN0#26920966
"""
return struct.pack('B', i)
def chr_encode(i):
"""Another method, from Quuxplusone's answer here:
https://codereview.stackexchange.com/a/210789/140921
Similar to g10guang's answer:
https://stackoverflow.com/a/51558790/8117067
"""
return chr(i).encode('latin1')
converters = [bytes_, to_bytes, struct_pack, chr_encode]
def one_byte_equality_test():
"""Test that results are identical for ints in the range [0, 255]."""
for i in range(256):
results = [c(i) for c in converters]
start = results[0]
if any(start != b for b in results):
raise ValueError(results)
def timing_tests(value=None):
"""Test each of the functions with a random int."""
if value is None:
value = random.randint(0, 255)
print(f'Testing with {value}:')
for c in converters:
print(f'{c.__name__}: ', end='')
timeit.main(args=shlex.split(
f"-s 'from int_to_byte import {c.__name__}; value = {value}' " +
f"'{c.__name__}(value)'"
))
("3" + "\r\n").encode()
有什么问题? - GLRoman