【问题标题】:Accurately testing Pypy vs CPython performance准确测试 Pypy 与 CPython 的性能
【发布时间】:2017-02-07 17:04:36
【问题描述】:

问题描述:

我有这个自定义的“校验和”功能:

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

我担心的是,由于potential JIT warmup overhead,我不确定timeit 是否适合PyPy 上的工作。

另外,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 实现中测试相同的确切函数性能的最佳和最准确的方法是什么?

【问题讨论】:

  • 那会测试(时间)什么吗?您似乎只执行了一个设置,没有真正的测试命令?
  • @MSeifert 啊,我是个白痴,你是绝对正确的。那里只设置了,我已经更新了答案,留下了问题的后半部分。谢谢!

标签: python performance benchmarking pypy


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您要测量的内容并不完全清楚。根据您的用例,“性能”可能意味着很多方面。

    • 您是否尝试在一切都预热后测量函数的原始速度(尤其是 JIT,还有库导入、文件加载等...)?然后你可能想--repeat 很像 Haroldo_OK 建议的。如果重复次数足够多,花在代码其他部分的时间会逐渐变得“微不足道”。
    • 您是为了学习还是为了真实世界的用例而测量事物?如果是后者,最好在类似条件下测试您的代码(传递给函数的字符串长度、迭代次数、代码的热/冷调用......)。我的印象是,使用 python interface 而不是 CLI 可以让您更灵活地准确衡量您的目标。

    值得注意的是,timeit turns off garbage collection,所以如果您正在寻找“真实世界”的测量值,也许您想重新打开它(请参阅链接了解如何操作)。

    如果您想提高速度,使用 Python3.6 和 pypy 都支持的像 cProfile 这样的分析器可以帮助隔离您要测量其速度的代码吗?

    我并没有真正回答你的问题,但我希望它会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 2011-10-27
      相关资源
      最近更新 更多