繁体   English   中英

为什么while循环比for循环花费的时间长?

[英]Why is does a while loop take longer than a for loop?

编辑:我按照一些评论说的做了更多次测试。 事实证明,在运行它们 10,000 次之后,while 循环稍微快一点,这是有道理的。 我的错。

我在 Python 中编写了两个最小公分母函数,一个使用 for 循环和三个导入,另一个使用 while 循环和一个导入。

# for loop
import sys
import operator as op
import functools as ft

def lcd(nums):
    if len(nums) < 2:
        return("Error: must be at least 2 numbers")
    elif 0 in nums:
        return("Error: cannot contain 0")
    else:
        nums = list(map(lambda x: abs(x), nums))
        highestLCD = ft.reduce(op.mul, nums) # multiply all nums together
        for i in range(max(nums),highestLCD,max(nums)):
            if all(i % n == 0 for n in nums):
                return i
        return highestLCD

if __name__ == "__main__":
    print(lcd([int(n) for n in sys.argv[1:]]))
# while loop
import sys

def lcd(nums):
    if len(nums) < 2:
        return("Error: must be at least 2 numbers")
    elif 0 in nums:
        return("Error: cannot contain 0")
    else:
        i = m = max(nums)
        while True:
            if all(i % n == 0 for n in nums):
                return i
            i += m

if __name__ == "__main__":
    print(lcd([int(n) for n in sys.argv[1:]]))

我预计 while 循环会更快,因为它的导入函数调用更少。

然而,在运行它们 1000 次之后,while 循环实际上慢了大约半秒到一整秒。

for

real    0m43.808s
user    0m29.016s
sys     0m10.164s
while

real    0m44.892s
user    0m29.528s
sys     0m10.565s

为什么是这样?

看到这个答案: 为什么在 Python 中循环 range() 比使用 while 循环更快?

似乎range()使事情比 i+=1 更有效率。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM