下面的两个代码段都检查数组中是否存在元素,但第一种方法需要<;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 ```
numpy是专门为加速这类代码而构建的,它是用c编写的,几乎消除了所有python开销,相比之下,您的第二次尝试是纯python,因此循环所有元素所需的时间要长得多
相关问题 更多 >
编程相关推荐