【问题标题】:python massive performance difference array iteration vs "if in"python巨大的性能差异数组迭代与“if in”
【发布时间】:2021-07-25 00:10:12
【问题描述】:

下面的代码 sn-ps 都会检查数组中是否存在元素,但第一种方法需要

有人知道为什么吗?

import numpy as np
import time

xs = np.random.randint(90000000, size=8000000)

start = time.monotonic()
is_present = -4 in xs

end = time.monotonic()

print( 'exec time:', round(end-start, 3) , 'sec ') // 100 milliseconds

start = time.monotonic()
for x in xs:
  if (x == -4):
    break

end = time.monotonic()

print( 'exec time:', round(end-start, 3) , 'sec ') // 6000 milliseconds ```

repl link

【问题讨论】:

  • 用 PyPy 而不是 CPython 试试这个,它神奇地快得多,而且差距越来越近。原因是 CPython 是一个(慢)解释器。第一行执行优化的本机 C 调用,而第二行使用解释器迭代列表(与使用本机编译代码相比,这非常慢)。

标签: python performance for-loop for-in-loop


【解决方案1】:

numpy 是专门为加速这类代码而构建的,它是用 c 编写的,几乎所有的 python 开销都被删除了,相对而言,你的第二次尝试是纯 python,所以循环所有元素需要更长的时间

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2019-04-21
    • 2010-10-15
    • 2011-12-18
    • 1970-01-01
    相关资源
    最近更新 更多