Edit: I did as some comments said and ran the test more times. Turns out, after running them both 10,000 times, the while loop is slightly faster, which would make sense. My bad.
I wrote two lowest common denominator functions in Python, one using a for loop and three imports, and the other using a while loop and one import.
# 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:]]))
I expected the while loop to be faster because it has fewer imports function calls.
However, after running them both 1000 times, the while loop is actually about half a second to a full second slower.
for
real 0m43.808s
user 0m29.016s
sys 0m10.164s
while
real 0m44.892s
user 0m29.528s
sys 0m10.565s
Why is this?