问题描述:
我有这个自定义的“校验和”函数:
NORMALIZER = 0x10000
def get_checksum(part1, part2, salt="trailing"):
"""Returns a checksum of two strings."""
combined_string = part1 + part2 + " " + salt if part2 != "***" else part1
ords = [ord(x) for x in combined_string]
checksum = ords[0] # initial value
# TODO: document the logic behind the checksum calculations
iterator = zip(ords[1:], ords)
checksum += sum(x + 2 * y if counter % 2 else x * y
for counter, (x, y) in enumerate(iterator))
checksum %= NORMALIZER
return checksum
我希望测试一下Python3.6和PyPy的性能差异,看看这个函数在PyPy上表现是否更出色。但我不确定最可靠、最简洁的方法是什么。
我尝试过的和我的问题:
目前,我在两种情况下都使用timeit
:
$ python3.6 -mtimeit -s "from test import get_checksum" "get_checksum('test1' * 100000, 'test2' * 100000)"
10 loops, best of 3: 329 msec per loop
$ pypy -mtimeit -s "from test import get_checksum" "get_checksum('test1' * 100000, 'test2' * 100000)"
10 loops, best of 3: 104 msec per loop
我的担忧是我不确定timeit
是否是用于在PyPy
上完成任务的正确工具,因为可能存在JIT预热开销。
此外,在报告测试结果之前,PyPy本身会报告以下内容:
WARNING: timeit is a very unreliable tool. use perf or something else for real measurements
pypy -m pip install perf
pypy -m perf timeit -s 'from test import get_checksum' "get_checksum('test1' * 1000000, 'test2' * 1000000)"
如何最好和最准确地测试相同的函数在这些以及其他可能的Python实现中的性能?