【发布时间】:2019-11-14 23:22:16
【问题描述】:
当我试图找出哪种解决方案更快时,我遇到了一个非常简单的问题并得到了一些奇怪的结果。
原始问题:给定两个列表ListA、ListB 和一个常量k,删除两个列表总和为k 的所有条目。
我通过两种方式解决了这个问题:首先我尝试使用循环,然后我使用列表理解和zip() 来压缩和解压缩这两个列表。
使用循环的版本。
def Remove_entries_simple(listA, listB, k):
""" removes entries that sum to k """
new_listA = []
new_listB = []
for index in range(len(listA)):
if listA[index] + listB[index] == k:
pass
else:
new_listA.append(listA[index])
new_listB.append(listB[index])
return(new_listA, new_listB)
使用列表理解和zip()的版本
def Remove_entries_zip(listA, listB, k):
""" removes entries that sum to k using zip"""
zip_lists = [(a, b) for (a, b) in zip(listA, listB) if not (a+b) == k]
# unzip the lists
new_listA, new_listB = zip(*zip_lists)
return(list(new_listA), list(new_listB))
然后我尝试确定哪种方法更快。但后来我得到了你在下图中看到的内容(x 轴:列表的大小,y 轴:运行它的平均时间,10**3 次重复)。出于某种原因,使用zip() 的版本总是在相同的位置进行相同的跳转——我在不同的机器上运行了多次。有人能解释一下是什么导致了这种奇怪的行为吗?
更新:我用来生成情节的代码。我使用函数装饰器将每个问题运行 1000 次。
导入语句:
import random
import time
import matplotlib.pyplot as plt
函数装饰器:
def Repetition_Decorator(fun, Rep=10**2):
''' returns the average over Rep repetitions'''
def Return_function(*args, **kwargs):
Start_time = time.clock()
for _ in range(Rep):
fun(*args, **kwargs)
return (time.clock() - Start_time)/Rep
return Return_function
创建图的代码:
Zippedizip = []
Loops = []
The_Number = 10
Size_list = list(range(10, 1000, 10))
Repeated_remove_loop = Repetition_Decorator(Remove_entries_simple, Rep=10**3)
Repeated_remove_zip = Repetition_Decorator(Remove_entries_zip, Rep=10**3)
for size in Size_list:
ListA = [random.choice(range(10)) for _ in range(size)]
ListB = [random.choice(range(10)) for _ in range(size)]
Loops.append(Repeated_remove_loop(ListA, ListB, The_Number))
Zippedizip.append(Repeated_remove_zip(ListA, ListB, The_Number))
plt.xlabel('Size of List')
plt.ylabel('Averaged time in seconds')
plt.plot(Size_list, Loops, label="Using Loop")
plt.plot(Size_list, Zippedizip, label="Zip")
plt.legend(loc='upper left', shadow=False, fontsize='x-large')
plt.show()
Update-Update:感谢 kaya3 指出 timeit 模块。
为了尽可能接近我的原始代码但也使用 timeit 模块,我创建了一个新的函数装饰器,它使用 timeit 模块对代码进行计时。
新的装饰器:
def Repetition_Decorator_timeit(fun, Rep=10**2):
"""returns average over Rep repetitions with timeit"""
def Return_function(*args, **kwargs):
partial_fun = lambda: fun(*args, **kwargs)
return timeit.timeit(partial_fun, number=Rep) / Rep
return Return_function
当我使用新的装饰器时,使用 for 循环的版本不受影响,但 zip 版本不再进行跳转。
到目前为止,我很确定跳跃是我如何测量函数而不是函数本身的结果。但是这种跳跃是如此明显——在不同的机器上总是以相同的列表大小——它不可能是侥幸。任何想法为什么会发生这种跳跃?
更新-更新-更新:
这与垃圾收集器有关,因为如果我用gc.disable() 禁用垃圾收集器,两种测量方式都会给出相同的结果。
我在这里学到了什么:不要只衡量自己的执行时间。使用timeit 模块来测量代码 sn-ps 的性能。
【问题讨论】:
-
有趣;请您也包括您用来分析它的代码吗?
-
我自己无法重现该行为;对于从 100 到 10,000 的大小,使用
zip的版本始终快约 30%。 -
你使用的是python 2还是python 3?这很重要,因为无论如何应该使用迭代器来完成整个事情。此问题中没有任何内容需要您创建任何临时列表。您真的想通过几个处理函数(根据您的标准删除)传输 2 个并行列表,然后从另一端输出。如果您在这里使用 py2,那么您正在使用当前实现创建很多临时列表。
-
我使用的是 Python 3.6.8。
-
@kaya3 添加了生成绘图的代码。感谢您的建议。
标签: python performance list-comprehension