The improvement in CPU usage comes from how lambda expressions are evaluated. Calling a lambda function will create a new stack frame each call, while a generator evaluates the expression on the same frame.
I'm on my mobile right now, but I can go into more detail later if you're interested.
9
u/not-na May 26 '19
I've tried three different variants:
Took 2.91s per loop.
Took 7.67s per loop.
Took 2.25s per loop.
All tested with an i7-7700 and Python 3.6.8 using timeit with 10 repeats.
It appears that
x**2is way slower thanx*xand using a generator is a bit faster than straight sum+map.I also noticed that during the generator benchmark, the CPU core that python was using wasn't as fully utilized as with the other variants.