我假设您想加快以下速度(Python3):
import struct
lst=list(range(100)) #any other size
struct.pack('i'*len(lst), *lst)
没有 struct 和 cython 你可以在 python 中实现如下:
import array
bytes(array.array('i', lst))
然而这比struct-module 慢一些:
>>> %timeit struct.pack('i'*len(lst), *lst)
2.38 µs ± 9.48 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit bytes(array.array('i',lst))
3.94 µs ± 92 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
不过,cython 可用于加快array 的创建速度,有关文档,请参阅here(arrays) 和here(str/bytes):
%%cython
import array
from cpython cimport array
def ser_int_list(lst):
cdef Py_ssize_t n=len(lst)
cdef array.array res=array.array('i')
array.resize(res, n) #preallocate memory
for i in range(n):
res.data.as_ints[i]=lst[i] #lst.__get__() needs Python-Integer, so let i be a python-integer (not cdef)
return res.data.as_chars[:n*sizeof(int)] # str for python2, bytes for python3
时序表现如下:
#list_size struct-code cython-code speed-up
1 343 ns 238 ns 1.5
10 619 ns 283 ns 2
100 2.38 µs 2.38 µs 3.5
1000 21.6 µs 5.11 µs 4
10000 266 µs 47.5 µs 5.5
即cython 提供了一些加速,从用于小型列表的 1.5 到用于大型列表的 5.5。
也许这可以进一步调整,但我希望你明白。
测试代码:
import struct
for n in [1, 10,10**2, 10**3, 10**4]:
print ("N=",n)
lst=list(range(n))
print("struct:")
%timeit struct.pack('i'*len(lst), *lst)
print("cython:")
%timeit ser_int_list(lst)