准确测试Pypy与CPython的表现

ale*_*cxe 17 python performance benchmarking pypy

问题描述:

我有这个自定义"校验和"功能:

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
Run Code Online (Sandbox Code Playgroud)

我想在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
Run Code Online (Sandbox Code Playgroud)

我担心的是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)"
Run Code Online (Sandbox Code Playgroud)

在这些以及可能的其他Python实现中测试相同的功能性能的最佳和最准确的方法是什么?

Har*_*_OK 3

您可以使用该参数增加重复次数--repeat以提高计时精度。看:

https://docs.python.org/2/library/timeit.html