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

Carl Cerecke cdc at maxnet.co.nz
Wed Jan 25 00:33:17 CET 2006


Adding a continue statemtent after the yield statements yields :-) a 
speed increase. Still not as good as functions though. (about 30% slower)

Cheers,
Carl

Carl Cerecke wrote:
> Carl Cerecke wrote:
> 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