Re[2]: [Tutor] script too slow

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Sat Mar 1 12:26:34 2003


Hello Paul,

Saturday, March 1, 2003, 7:08:21 PM, you wrote:

PT> Hmm. Overall, my the second part of my module ran about 3 times faster
PT> when I used dictionaries rather than elif. However, I changed several
PT> things at once, so I guess I would have to change just one part of my
PT> code and test it.
It might depend on amount of if-elif-else parts.

>> And the last note: self.dict_token.get should take some valuable time.
>> You might be better with passing self.dict_token.get in all the
>> functions as a parameter

PT> This suggestion confuses me. So far as I can tell, I'm using the lookup
PT> only in one function, when I have to. Each token gets only one lookup if
PT> it starts with a "\\". Can you give me an example?
If I understand it correctly, self.dict_token.get is resolved each
time you call the function. It takes two lookups and might be
expensive. Alternative approach might be to store self.dict_token.get
as a bound method and call it than needed.

Here comes a simple example of the technic:

<code>
d = {
    "aaa": 1,
    "bbb": 2,
    "ccc": 3,
}

keys = ["ccc", "aaa", "bbb", "ddd", "eee", "fff", "ggg"]

getter = d.get # Here we got a bound method

def f1(d):
    for k in keys:
        x = d.get(k) # Takes one lookup more
    
def f2(getter):
    for k in keys:
        x = getter(k) # Calling bound method
    
import time
def clock_func(f, params):
    t = time.clock()
    for i in range(1000):
        f(*params)
    print "%s:\t%06f" % (f.__name__, time.clock() - t)
    
def main():
    clock_func(f1, (d,))
    clock_func(f2, (getter,))
    
main()
<\code>

In average it prints something like:
f1:     0.013130
f2:     0.010207

Your gain might be even more as you need two lookups.

Somewhere in the Web ;) there is really nice article by Guido about
optimization, try to Google for it.

-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru