我写了一些非常简单的测试(我知道,它们不是“结论性的”,但它们让我很好奇)。我跑着优化和所有的爵士乐。
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()
我得到了结果:
> All even: 2.86299991608
> All even bad: 3.71399998665
> All one: 3.89900016785
看来内置功能不会提前退出?