Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

python - for loop vs. all() execution speed

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

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's your hint:

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...