Generators vs. Functions?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Feb 5 13:12:11 EST 2006


On Sun, 05 Feb 2006 16:14:54 +0000, Neil Schemenauer wrote:

> Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
>> Have you actually measured this, or are you just making a wild
>> guess?
> 
> I haven't timed it until now but my guess it not so wild.  I'm
> pretty familiar with the generator implementation (having written
> the initial version of it).

Well I guess you're forgiven then *sheepish grin*

> In Python 2.3, resuming a generator
> does a small amount of setup and then calls eval_frame().  Calling a
> function does more setup work and then also calls eval_frame().

It takes MORE setup to call a function than it takes to resume a
generator?


>> Here is my test, using Python 2.3. I've tried to make the test as
>> fair as possible, with the same number of name lookups in both
>> pieces of test code.
> 
> On my machine t4 is faster than t3.  Your test is not so fair
> because the generator is doing a "while" loop (executing more
> bytecode instructions) while the function is just returning a value
> (one instruction).

A fair criticism, but then a generator with just one instruction is, well,
pointless.

 
> On your machine the function call may be faster due to CPU cache
> effects or branch prediction.  In any case, the difference you are
> trying to measure is extremely small.  Try adding some arguments to
> the functions (especially keyword arguments).


Small in absolute terms, but significant in relative terms: as an order of
magnitude, a factor of about 1/10th.

Of course, I never expected that calling/resuming cost to be significant
for most real world uses. If I gave anyone that impression, it wasn't
intended.

> What your test does show is that the speed difference should not
> come into the decision of which construct to use.

I never said it should.



-- 
Steven.




More information about the Python-list mailing list