Are python generators faster than nested for loops

2019-08-17 14:22发布

问题:

I having some problems trying to understand generators.

Do these function's execution time differ when doing the same task?

def slow_sum(size):
    x= 0
    for i in range(size):
        for j in range(size):
            x += i + j
    return x

def fast_sum(size):
    return sum( [ (i+j) for j in range(size) for i in range(size)] )

size = 2000
slow_val = slow_sum(size)
fast_val = fast_sum(size)
assert slow_val == fast_val, "Values are not equal"

When profiling both functions on my computer using cProfile I got these result, but I expected them to be similar.

Total Time

  • slow_sum(2000)

    • 0.85 ms
  • fast_sum(2000)

    • 0.05 ms

Original File: https://pastebin.com/fDfaSqyZ

My Output: https://pastebin.com/wyy3v3iy

回答1:

You're looking at the wrong column of the profiler output. tottime doesn't count all the time fast_sum spends inside the sum call or the list comprehension's stack frame. You should be looking at cumtime, which is near equal for the two functions.