performance question

Raymond Hettinger python at rcn.com
Thu Mar 15 02:46:29 EDT 2007


[Eric Texier]
> I need speed here. What will be the fastest method or does it matter?
Follow Alex's advice and use the timeit module, but do not generalize
from too small examples; otherwise, the relative timings will be
thrown-off by issues like the time to lookup "write" and "a" and "str"
(all of which will be faster if made a local).  Likewise, do the
timings with the actual expected vector length.


> (for the example 'a' is only 3 values for the clarity of the example)
> a = [1,3,4.] ##
> f.write("vec %f %f %f \n" % (a[0],a[1],a[2]))

It's a waste of time to lookup and repack with (a[0],a[1],a[2]).
Instead, try:
    f.write('vec %f %f %f' % tuple(a))


> f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n")

Often, it is better to join than to make successive concatenations:

   f.write('vec' + ' '.join(map(str, a)))


> also it there a relevant speed difference between making few small write
> instead of 1 bigger one.

Yes.  One big one is faster than many small.


Raymond




More information about the Python-list mailing list