Are python generators faster than nested for loops? [closed]

≡放荡痞女 提交于 2019-12-11 15:39:25

问题


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.



来源:https://stackoverflow.com/questions/54382727/are-python-generators-faster-than-nested-for-loops

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!