python如何像zlib.adler32一样快速地计算简单的校验和

2024-09-28 15:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算一个简单的校验和:只需添加所有字节的值。

我找到的最快的方法是:

checksum = sum([ord(c) for c in buf])

但是对于13mb的数据buf,需要4.4s:太长(在C语言中,需要0.5s)

如果我使用:

checksum = zlib.adler32(buf) & 0xffffffff

它需要0.8秒,但结果不是我想要的。

所以我的问题是:Python2.6中是否有任何函数、lib或C来计算简单的校验和?

提前谢谢你, 埃里克。


Tags: 数据方法函数infor字节lib校验
2条回答

您可以使用sum(bytearray(buf))

In [1]: buf = b'a'*(13*(1<<20))

In [2]: %timeit sum(ord(c) for c in buf)
1 loops, best of 3: 1.25 s per loop

In [3]: %timeit sum(imap(ord, buf))
1 loops, best of 3: 564 ms per loop

In [4]: %timeit b=bytearray(buf); sum(b)
10 loops, best of 3: 101 ms per loop

以下是用Cythonsumbytes.pyx文件编写的Python的C扩展名:

from libc.limits cimport ULLONG_MAX, UCHAR_MAX

def sumbytes(bytes buf not None):
    cdef:
        unsigned long long total = 0
        unsigned char c
    if len(buf) > (ULLONG_MAX // <size_t>UCHAR_MAX):
        raise NotImplementedError #todo: implement for > 8 PiB available memory
    for c in buf:
        total += c
    return total

sumbytesbytearray变体快约10倍:

name                    time ratio
sumbytes_sumbytes    12 msec  1.00 
sumbytes_numpy     29.6 msec  2.48 
sumbytes_bytearray  122 msec 10.19 

要重新生成时间度量,请下载^{}并运行:

#!/usr/bin/env python
# compile on-the-fly
import pyximport; pyximport.install() # pip install cython
import numpy as np 
from reporttime import get_functions_with_prefix, measure    
from sumbytes import sumbytes # from sumbytes.pyx

def sumbytes_sumbytes(input):
    return sumbytes(input)

def sumbytes_bytearray(input):
    return sum(bytearray(input))

def sumbytes_numpy(input):
    return np.frombuffer(input, 'uint8').sum() # @root's answer

def main():
    funcs = get_functions_with_prefix('sumbytes_')
    buf = ''.join(map(unichr, range(256))).encode('latin1') * (1 << 16)
    measure(funcs, args=[buf])

main()

使用numpy.frombuffer(buf, "uint8").sum(),它似乎比您的示例快70倍:

In [9]: import numpy as np

In [10]: buf = b'a'*(13*(1<<20))

In [11]: sum(bytearray(buf))
Out[11]: 1322254336

In [12]: %timeit sum(bytearray(buf))
1 loops, best of 3: 253 ms per loop

In [13]: np.frombuffer(buf, "uint8").sum()
Out[13]: 1322254336

In [14]: %timeit np.frombuffer(buf, "uint8").sum()
10 loops, best of 3: 36.7 ms per loop

In [15]: %timeit sum([ord(c) for c in buf])
1 loops, best of 3: 2.65 s per loop

相关问题 更多 >