I have wrote some very simple tests (I know, they are not 'conclusive', but they make me curious). I ran with optimization and all that jazz.
from time import time
alist = [ 2, 4, 6, 8, 10, 12, 24, 48, 64, 128 ]
def all_even( alist ):
for val in alist:
if not (val & 1) == 0:
return False
return True
def all_even_bad( alist ):
result = False
for val in alist:
if not (val & 1) == 0:
result = False
else:
result = True
return result
def main():
start = time()
for i in range(1, 10000):
all_even( alist )
print('All even: {0}'.format(time() - start))
start = time()
for i in range(1, 10000):
all_even_bad( alist )
print('All even bad: {0}'.format(time() - start))
start = time()
for i in range(1, 10000):
all( val & 1 == 0 for val in alist )
print('All one: {0}'.format(time() - start))
if __name__ == '__main__':
main()
I get results around:
> All even: 2.86299991608
> All even bad: 3.71399998665
> All one: 3.89900016785
It appears the built in function doesn't bail out early?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…