for循环vs. all()执行速度 [英] for loop vs. all() execution speed

查看:82
本文介绍了for循环vs. all()执行速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我认为下面的两个代码片段基本上应该做同样的事情:

Hello I think the two snippet below should essentially do the same thing:

for divisor in range(2, 21):
    if sample % divisor != 0:
        break

第一个代码段,我使用sample除以2到20的数字,如果其中任何一个给出余数!= 0,那么我将break尝试sample += 1(省略代码)

The first snippet, I use sample divided by number from 2 to 20, if any one of them gives remainder != 0, then I will break and try sample += 1 (codes omitted)

if all(sample % divisor == 0 for divisor in range(2, n2+1)):
    return sample

如果all()True一起返回,我将返回第二个片段,否则,我将尝试sample += 1(省略代码)

The second snippet I will return the sample if all() comes back with True, otherwise I will try sample += 1 (codes omitted)

发现第二个片段比第一个片段慢两倍.我不明白,当python评估all()时,如果在迭代中找到一个False,它应该立即返回False for all(),而不是完成整个迭代,对吧?

The second snippet is found twice slower than the first one. I don't understand, when python evaluate all(), if one False was found in iteration, it should immediately comes back False for all(), instead of finish the whole iteration, right?

那么为什么第二个片段比第一个片段慢?

So why is the second snippet slower than the first one?

推荐答案

这是您的提示:

>>> (sample % divisor == 0 for divisor in range(2, n2+1))
<generator object <genexpr> at 0x10ead7a00>

您的代码正在创建一个genexp,并要求all一遍又一遍地对该genexp调用next方法.

Your code is creating a genexp, and requiring all to call the next method on that genexp over and over.

在不涉及任何函数调用的for循环上,这不可避免地会降低性能.另请参见 Python:为什么列表理解要比for循环慢 a>

This has an unavoidable performance penalty over a for loop involving no function calls. See also Python: Why is list comprehension slower than for loop

这篇关于for循环vs. all()执行速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆