Python将byte数组转换为int详解编程语言

代码

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 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8520.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论