@simple_mark_time
def func1(aa):bb = [0] * aa.shape[1]for i in range(aa.shape[0]):row = aa[i]bb = [row[i] + bb[i] for i in range(len(row))]return bb@simple_mark_time
def func2(aa):bb = np.full((aa.shape[1],), 0, dtype=np.float64)for i in range(aa.shape[0]):row = aa[i]bb += rowreturn bbif __name__ == "__main__":a = np.random.random((531, 17280))b1 = func1(a) # func1 use time = 2.3398b2 = func2(a) # func2 use time = 0.008print(np.all(np.array(b1) == b2)) # True
@simple_mark_time
def func1(aa):bb = np.full((500, 17280), np.nan, dtype=np.float64)for i in range(aa.shape[0]):row = aa[i]bb[i] = rowreturn bb@simple_mark_time
def func2(aa):bb = []for i in range(500):if i < aa.shape[0]:row = aa[i]else:row = np.full((17280,), np.nan, dtype=np.float64)bb.append(row)bb = np.array(bb)return bbif __name__ == "__main__":a1 = np.random.random((50, 17280))b1 = func1(a1) # func1 use time = 0.015b2 = func2(a1) # func2 use time = 0.0489print(np.all(b1[~np.isnan(b1)] == b2[~np.isnan(b2)])) # Truea2 = np.random.random((500, 17280))b1 = func1(a2) # func1 use time = 0.03b2 = func2(a2) # func2 use time = 0.0369print(np.all(b1[~np.isnan(b1)] == b2[~np.isnan(b2)])) # True
sum 函数改为 np.sum 函数验证实例:【Python性能优化实例】计算 numpy 数组首尾为 0 的数量
验证实例:【Python性能优化】元素极少时list和set的查找速度
A 而不存在于集合 B 的,那么遍历差集(A - B)的性能将由于遍历并集(A | B)后,再判断是否只在集合 A 中存在O(N) 的性能,因此如果集合需要多次使用,则不妨先将集合存储下来.items() 将获得更好的性能get 方法_source 进行请求