Python将byte数组转换为int
2018-07-20 来源:open-open
代码
import struct import ctypes def test_struct(buf, offset): return struct.unpack_from("I", buf, offset)[0] def test_ctypes(buf, offset): return ctypes.c_uint32.from_buffer(buf, offset).value def test_multi(buf, offset): return buf[offset] + (buf[offset+1] << 8) + (buf[offset+2] << 16) +(buf[offset+3] << 24) buf_w = bytearray(5) buf_w[1] = 1 buf_r = buffer(buf_w) if __name__ == '__main__': import timeit t1 = timeit.Timer("test_struct(buf_r, 1)", "from __main__ import test_struct, buf_r") t2 = timeit.Timer("test_ctypes(buf_w, 1)", "from __main__ import test_ctypes, buf_w") t3 = timeit.Timer("test_multi(buf_w, 1)", "from __main__ import test_multi, buf_w") print t1.timeit(number=1000) print t2.timeit(number=1000) print t3.timeit(number=1000)
结果
number = 10000 0.0081958770752 0.012549161911 0.0112121105194 number = 1000 0.00087308883667 0.00125789642334 0.00110197067261 number = 100 0.0000917911529541 # 9.17911529541e-05 0.000133991241455 0.00011420249939 number = 10 1.69277191162e-05 2.19345092773e-05 1.69277191162e-05 number = 1 1.00135803223e-05 1.00135803223e-05 5.96046447754e-06
标签: 代码
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:Python发邮件带附件
下一篇:在Shell中使用日期运算和比较
最新资讯
热门推荐