Making code faster
Bengt Richter
bokr at oz.net
Wed Jul 17 11:56:49 EDT 2002
On Wed, 17 Jul 2002 12:06:39 +0200, JB <jblazi at hotmail.com> wrote:
>Bengt Richter wrote:
>
>>>[<string>,<string>]
>> - Do you mean that literally? I.e., would
>> "['abc','def']\n"
>> be a valid example?
>> - Why do you have to eval() it? That is probably
>> timeconsuming compared to alternatives.
>
>I thought, that would be fast. I can choose the format that
>is best. (But probably, I 'd like to have a text format.)
>So I could shoose
>abc def
Simple is generally good ;-)
>too.
>
>> - Are there always two elements in the list?
>Yes.
>
>Now I have changed my program to
>
> i = -1
> print 'loading file'
> def tmp1(s,color=self.sv.lv.newColor):
> global i
> i += 1
> j = string.find(s,' ')
> return QSimpleViewItem(i,color,[s[:j],s[j+1:-1]])
Replacing the above 2 lines with the following one should be faster:
return QSimpleViewItem(i,color,s.split())
It assumes you have an s from your file that looks like
<opt ws><item1 with no embedded whitespace><ws><item2 with no embedded whitespace><opt ws>
Where <opt ws> is one or more optional white space characters [ \t\r\n\f]
and <ws> is at least one white space character.
Note how split() works:
>>> 'abc def'.split()
['abc', 'def']
>>> 'abc def\n'.split()
['abc', 'def']
>>> ' abc def \n'.split()
['abc', 'def']
>>> ' abc def \n '.split()
['abc', 'def']
>>>
>
> try:
> myfile = open(filename)
> except:
> pass
> else:
> tmp = myfile.readlines()
> print 'lines loaded'
> myfile.close()
> self.sv.lv.rows = map(tmp1,tmp)
> self.sv.lv.visible = range(len(self.sv.lv.rows))
> print 'lines decoded',self.sv.lv.rows[0].col[0]
>
>This is really faster. I did not undertand, how to get rid
>of the global variable <i>, but even if I do not use i at
>all and replace it by 0, the time I need is the same.
>
That was a good experiment, showing that global/local is
insignificant compared to other overheads in this particular
loop. But if you have a loop where the other stuff is really fast,
you will notice a difference when you execute enough loops.
Regards,
Bengt Richter
More information about the Python-list
mailing list