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