Eric Texier <[EMAIL PROTECTED]> wrote: > I need speed here. What will be the fastest method or does it matter? > > (for the example 'a' is only 3 values for the clarity of the example) > a = [1,3,4.] ## > > > method1: > > f.write("vec %f %f %f \n" % (a[0],a[1],a[2])) > > method2: > > f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n") > > also it there a relevant speed difference between making few small write > instead of 1 bigger one.
Learn to use the timeit module from the standard library, particularly via the handy -mtimeit commandline switch, and you can measure performance issues for yourself. E.g., on my laptop: brain:~ alex$ python -mtimeit -s"a=[1,3,4];f=open('/dev/null','w')" 'f.write("vec %f %f %f \n" % (a[0],a[1],a[2]))' 100000 loops, best of 3: 5.64 usec per loop brain:~ alex$ python -mtimeit -s"a=[1,3,4];f=open('/dev/null','w')" 'f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n")' 100000 loops, best of 3: 3.36 usec per loop So, the ugly "method 2" is about 2.3 microseconds faster than the nicer "method 1" -- when the items of a are ints which method 1 widens to floats while method 2 doesn't (the results are different between the methods). When they're floats to start with...: brain:~ alex$ python -mtimeit -s"a=[1.,3.,4.];f=open('/dev/null','w')" 'f.write("vec %f %f %f \n" % (a[0],a[1],a[2]))' 100000 loops, best of 3: 5.45 usec per loop brain:~ alex$ python -mtimeit -s"a=[1.,3.,4.];f=open('/dev/null','w')" 'f.write("vec " + str(a[0]) + " " + str(a[1]) + " " + str(a[2]) + "\n")' 100000 loops, best of 3: 6.26 usec per loop then method 1 accelerates a little bit and method 2 slows down a lot, so method 1 is actually about 0.8 microseconds faster. Make sure you do your measurements with data that well represents your actual application needs, and -mtimeit will serve you well (if you don't care about that microsecond or two either way, which is often the case, then choose the nicer metod 1, of course:-). Alex -- http://mail.python.org/mailman/listinfo/python-list