-1

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?

deNoww
  • 83
  • 8
  • 2
    This is not you benchmark! Your test size is small. The test env are not equal. Many other problems. – clamentjohn Feb 12 '19 at 10:57
  • Please rerun these tests using timeit and post results: https://docs.python.org/2/library/timeit.html – Neil Feb 12 '19 at 10:59
  • Also there's an explicit upper bound on the `for` loop which the `while` loop doesn't have – meowgoesthedog Feb 12 '19 at 10:59
  • Err ... if you want to compare for/while loops you would need to make sure that the algorithm using those iterations is the same ... not merely similar, before ensuring that you might as well take a guess.(btw: to have a closer look throw the functions into dis.dis after importing 'dis') – meissner_ Feb 12 '19 at 11:03
  • @meissner_ The point wasn't to compare while loops to for loops, it was to compare the two algorithms. The one that used the while loop was optimised for using a while loop, and the one that used the for loop was optimised for using a for loop. – deNoww Feb 12 '19 at 11:14

1 Answers1

0

See this answer: Why is looping over range() in Python faster than using a while loop?

It seems that range() makes things more efficient that the i+=1.

  • Thanks! Turns out I just didn't run enough tests. 10,000 times shows the while loop being ~10/5/2s faster. – deNoww Feb 12 '19 at 12:16