有没有更有效的方法将0..255(在C uint8中)范围内的整数转换为1字节?
x = 100
x.to_bytes(1, "big")
有没有更有效的方法将0..255(在C uint8中)范围内的整数转换为1字节?
x = 100
x.to_bytes(1, "big")
对单个整数更有效的方法?大概不会吧.
以下是常见的几种方法的比较:
python -m timeit -s "import struct" "struct.pack('<B', 100)"
2000000 loops, best of 5: 101 nsec per loop
python -m timeit "(100).to_bytes(1)"
5000000 loops, best of 5: 81.1 nsec per loop
python -m timeit "bytes([100])"
2000000 loops, best of 5: 199 nsec per loop
如果你说的是倍数,bytes([integers])
可能是最有效的.
对于一些过早的优化,您可以缓存函数,这将使您获得几纳秒的时间:
python -m timeit -s "tb = int.to_bytes" "tb(100,1)"
5000000 loops, best of 5: 78.6 nsec per loop
如果您想要尽可能高效,它可能会使用元组:
python -m timeit -s "b=tuple(map(int.to_bytes, range(256)))" "b[100]"
10000000 loops, best of 5: 20.9 nsec per loop
但就我个人而言,我觉得这很恶心.