如何解决为什么numpy在两个数组中比较按元素的较大值时不快?
我有三个函数版本,可以对两个列表进行逐元素比较,并输出结果计数。第一次使用for循环(简单函数),第二次使用列表表达式,第三次使用numpy。我希望numpy会超级快,尤其是在列表很大时一次,但是发现它并不一致。
在具有不同数组大小的google colab上运行此命令,结果如下: SN)ArraySize RuntimeRatio =简单:已优化:脾气暴躁
- 25 1:0.43:2.61
- 25 1:0.22:0.46
- 25 1:0.63:0.29
- 25 1:0.75:1.18
- 2500 1:0.89:3.07
- 2500 1:0.84:1.51
- 2500 1:0.59:0.79
- 2500 1:0.75:2.19
- 250000 1:1.26:2.64
- 250000 1:1.23:2.18
- 250000 1:1.25:2.22
- 250000 1:0.90:1.56
- 25000000 1:1.40:2.25
- 25000000 1:1.32:2.22
- 25000000 1:1.29:2.17
- 25000000 1:1.28:2.19
关于发生的事情或我做错了什么的想法?
代码:
import numpy as np
import time
import random
def solution_list_simple(a,b):
answer = 0
for aval,bval in zip(a,b):
if aval > bval:
answer += 1
return answer
###########
def solution_list_opti(a,b):
return [ a_ele > b_ele for a_ele,b_ele in zip(a,b) ].count(True)
###########
def solution_np(a,b):
return np.sum( np.array(a) > np.array(b) )
###########
random.seed(30)
howmanyvalue = 250000
A = [ random.randint(1,100) for _ in range(howmanyvalue) ]
B = [ random.randint(1,100) for _ in range(howmanyvalue) ]
## list version - simple
start_time = time.time()
print(f"")
print(f"\nanswer list simple = {solution_list_simple(A,B)}")
runtime_list_simple = time.time() - start_time
print(f"Runtime list simple = {runtime_list_simple}")
## list version - optmised
start_time = time.time()
print(f"")
print(f"\nanswer list_opti = {solution_list_opti(A,B)}")
runtime_list_opti = time.time() - start_time
print(f"Runtime list optimised = {runtime_list_opti}")
## numpy version
start_time = time.time()
print(f"")
print(f"\nanswer numpy = {solution_np(A,B)}")
end_np = time.time()
runtime_numpy = time.time() - start_time
print(f"Runtime numpy = {runtime_numpy}")
print(f"\n\nRelative ratios\nlist_simple : list_optimised : numpy = {1} : {(runtime_list_opti / runtime_list_simple):.2f} : {(runtime_numpy / runtime_list_simple):.2f}")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。