python大规模性能差异数组迭代与“if in”

2024-05-13 18:16:52 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的两个代码段都检查数组中是否存在元素,但第一种方法需要<;100毫秒,而第二次进近需要约6秒

有人知道为什么吗

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


Tags: inimporttime代码段np数组secstart