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
189 views
in Technique[技术] by (71.8m points)

python - Why is any (True for ... if cond) much faster than any (cond for ...)?

Two similar ways to check whether a list contains an odd number:

any(x % 2 for x in a)
any(True for x in a if x % 2)

Timing results with a = [0] * 10000000 (five attempts each, times in seconds):

0.60  0.60  0.60  0.61  0.63  any(x % 2 for x in a)
0.36  0.36  0.36  0.37  0.37  any(True for x in a if x % 2)

Why is the second way almost twice as fast?

My testing code:

from timeit import repeat

setup = 'a = [0] * 10000000'

expressions = [
    'any(x % 2 for x in a)',
    'any(True for x in a if x % 2)',
]

for expression in expressions:
    times = sorted(repeat(expression, setup, number=1))
    print(*('%.2f ' % t for t in times), expression)

Try it online!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The first method sends everything to any() whilst the second only sends to any() when there's an odd number, so any() has fewer elements to go through.


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

...