Weird generator id() behaviour (was Re: Python code written in1998, how to improve/change it?)

Carl Cerecke cdc at maxnet.co.nz
Wed Jan 25 00:27:05 CET 2006


Carl Cerecke wrote:
> Fredrik Lundh wrote:
> 
>> Carl Cerecke wrote:
>>
>>
>>> It turns out that generators are more efficient than the eval function
>>> excuting bits of compiled code. About 20-25% faster.
>>
>>
>>
>> why are you using generators to return things from a function, when
>> you can just return the things ?
> 
> 
> Trying to find the fastest way to implement finite state machine.
> The included file times 4 different ways, with functions the fastest.
> 
> The reason, I think, for the unusual sequence if id()s of the generators 
> - see grandparent post - (and the reason for their poor performance 
> compared to functions), is because the reference to the generator is 
> being lost, then another generator is being created with the same id.
> Properly done, I would expect generators to out perform functions.

Generator FSM done properly (well, better anyway). They are still almost 
twice as slow as plain function calls, though.

def g_on():

     while 1:
         action = next_action()
         if action == 'lift':
             yield s_g_on
         elif action == 'push':
             yield s_g_off
         else:
             break
     yield None

def g_off():

     while 1:
         action = next_action()
         if action == 'lift':
             yield s_g_on
         elif action == 'push':
             yield s_g_off
         else:
             break
     yield None

def actions(n):
     import random
     for i in range(n-1):
         yield random.choice(['lift','push'])
     yield None

r = 1000000
#r = 10
next_action = actions(r).next
s_g_on = g_on()
s_g_off = g_off()
state = s_g_on

while state:
     state = state.next()
z = time.clock()



More information about the Python-list mailing list