【发布时间】: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 ```
【问题讨论】:
-
用 PyPy 而不是 CPython 试试这个,它神奇地快得多,而且差距越来越近。原因是 CPython 是一个(慢)解释器。第一行执行优化的本机 C 调用,而第二行使用解释器迭代列表(与使用本机编译代码相比,这非常慢)。
标签: python performance for-loop for-in-loop