【问题标题】:Strange performance results -- loop vs list comprehension and zip()奇怪的性能结果——循环与列表理解和 zip()
【发布时间】:2019-11-14 23:22:16
【问题描述】:

当我试图找出哪种解决方案更快时,我遇到了一个非常简单的问题并得到了一些奇怪的结果。

原始问题:给定两个列表ListAListB 和一个常量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


【解决方案1】:

这似乎是您测量运行时间的方式的产物。我不知道是什么导致您的计时代码产生这种效果,但是当我使用timeit 来测量运行时间时,效果消失了。我正在使用 Python 3.6.2。

我可以使用您的时序代码始终如一地重现该效果;我得到zip 版本的运行时间在相同的阈值附近跳跃,尽管它仍然比我机器上的其他版本略快:

但是,当我使用timeit 测量时间时,效果完全消失了:

这是使用timeit的代码;我尽量少改动你的分析代码。

import timeit

Zippedizip = []
Loops = []
The_Number = 10
Size_list = list(range(10, 1000, 10))
Reps = 1000

for size in Size_list:
    ListA = [random.choice(range(10)) for _ in range(size)]
    ListB = [random.choice(range(10)) for _ in range(size)]

    remove_loop = lambda: Remove_entries_simple(ListA, ListB, The_Number)
    remove_zip = lambda: Remove_entries_zip(ListA, ListB, The_Number)

    Loops.append(timeit.timeit(remove_loop, number=Reps) / Reps)
    Zippedizip.append(timeit.timeit(remove_zip, number=Reps) / Reps)

# ...

所以我认为这是一个虚假的结果。也就是说,我不明白是什么导致了你的计时代码。我尝试简化您的计时代码以不使用装饰器或 vargs,并将time.clock() 替换为更准确的time.perf_counter(),但这并没有改变任何东西。

【讨论】:

  • 感谢您的建议。我将timeit 函数放入装饰器中,效果消失了。我仍然不知道为什么其他装饰器总是让这个跳转出现。
【解决方案2】:

使用 zip 并行遍历列表同时使用 append 进行总和的版本似乎更加一致。

我认为我们在zip(*...) 中看到的是,将 (*) 迭代到参数列表中具有一定的阈值(可能是 768 个参数?),之后会使用较慢的方法。

def Remove_entries_halfzip(listA, listB, k):
    """ removes entries that sum to k using zip"""
    new_listA = []
    new_listB = []
    for a, b in zip(listA, listB):
        if a + b != k:
            new_listA.append(a)
            new_listB.append(b)

    return (new_listA, new_listB)

您可以通过将附加函数设为本地来进一步进行微优化,为每次迭代保存一个属性查找:

def Remove_entries_halfzip_micro_opt(listA, listB, k):
    """ removes entries that sum to k using zip"""
    new_listA = []
    new_listB = []
    append_a = new_listA.append
    append_b = new_listB.append
    for a, b in zip(listA, listB):
        if a + b != k:
            append_a(a)
            append_b(b)

    return (new_listA, new_listB)

我也尝试了一个 Numpy 实现,但由于需要进行数据转换(np.array() 每次调用都会强制转换),所以速度较慢。如果您一直在使用 Numpy 数组,它会更快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2017-05-19
    • 2016-05-26
    • 1970-01-01
    • 2018-11-07
    • 2017-05-14
    • 2013-06-27
    相关资源
    最近更新 更多