直观对比几个不同 Python 代码片段的运行速度
写 Python 脚本经常需要处理大量数据,某些操作一旦没注意就会耗时巨大,造成「code 一时爽,耗时火葬场」……
import numpy as np
from tqdm import tqdm
import time
小任务:对列表B的每一个元素,寻找与列表A中差值的绝对值最小的index,添加到C中
A = np.random.rand(10000)
B = np.random.rand(10000)
[快速版本] 使用 argmin 直接返回
ss = time.time()
C = [abs(A - b).argmin() for b in tqdm(B)]
ee = time.time()
print('cost {}'.format(ee - ss))
100%|██████████| 10000/10000 [00:00<00:00, 39883.84it/s]
cost 0.2566795349121094
[龟速版本] for-loop 遍历查找
ss = time.time()
C = []
for b in tqdm(B):
min_i = -1
min_d = float('inf')
for i, a in enumerate(A):
d = abs(a - b)
if d < min_d:
min_d = d
min_i = i
C.append(min_i)
ee = time.time()
print('cost {}'.format(ee - ss))
100%|██████████| 10000/10000 [00:45<00:00, 217.41it/s]
cost 45.99927496910095
小任务:对列表B的每一个元素,寻找是否为列表A某个元素的属性,有则把对应的index添加到C中
class Apple(object):
def __init__(self, a):
self.a = a
A = [Apple(a) for a in np.random.randint(1, 10000, 10000)]
B = np.random.randint(1, 10000, 10000)
[快速版本] 预先使用字典做好对应
ss = time.time()
A_keys = {one.a: index for index, one in enumerate(A)}
C = [A_keys[b] for b in tqdm(B) if b in A_keys]
ee = time.time()
print('cost {}'.format(ee - ss))
100%|██████████| 10000/10000 [00:00<00:00, 2108220.16it/s]
cost 0.008636236190795898
[龟速版本] 通过列表的 index 返回
ss = time.time()
C = []
A_keys = [one.a for one in A]
for b in tqdm(B):
if b in A_keys:
C.append(A_keys.index(b))
ee = time.time()
print('cost {}'.format(ee - ss))
100%|██████████| 10000/10000 [00:01<00:00, 5652.18it/s]
cost 1.7722303867340088
本作品采用《CC 协议》,转载必须注明作者和本文链接