[英]python massive performance difference array iteration vs "if in"
Both the code snippets below check if an element exists in the array but first approach takes < 100ms while the second approach takes ~6 seconds.下面的两个代码片段都检查数组中是否存在元素,但第一种方法需要 < 100 毫秒,而第二种方法需要约 6 秒。
Does anyone know why?有谁知道为什么?
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 is specifically built to accelerate this kind of code, it is written in c with almost all of the python overhead removed, comparatively your second attempt is pure python so it takes much longer to loop through all the elements numpy is specifically built to accelerate this kind of code, it is written in c with almost all of the python overhead removed, comparatively your second attempt is pure python so it takes much longer to loop through all the elements
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.