[Tutor] string formatting

Steven D'Aprano steve at pearwood.info
Tue Sep 20 03:11:42 CEST 2011


Wayne Werner wrote:
> On Mon, Sep 19, 2011 at 1:11 PM, <bodsda at googlemail.com> wrote:
> 
>> Is there any additional overhead of using the locals() or format(locals())
>> instead of a tuple? - the format option is a double function call so I would
>> expect that to be considerably slower
>>
> 
> Using the following code and timeit, it appears that there is a difference,
> but unless you call 0.3-6 ns considerable (assuming I got my math correct:
> The difference was ~1.2 or ~1.3 seconds for the classic, ~1.9 for the %
> locals version, and timeit runs 1,000,000 times with the default settings),
> then the difference isn't terrible.

I get similar speeds with Python 2.7:

 >>> for f in [withargs, classicwithtuple, classicwithlocals]:
...     t = timeit.Timer(f)
...     print(t.timeit())
...
1.72170519829
1.18233394623
1.96000385284


However, a single reading with timeit is subject to a lot of noise. 
Trying again:


 >>> for f in [withargs, classicwithtuple, classicwithlocals]:
...     t = timeit.Timer(f)
...     print(min(t.repeat(repeat=5)))  # Best of five runs.
...
1.19279980659
1.01878404617
1.56821203232

So, roughly speaking, it looks like the format method is about 20% 
slower than % with a tuple, and using locals is about 60% slower.



-- 
Steven



More information about the Tutor mailing list