RSS

Tag Archives: tuple

timeit测试Python中tuple格式化字符串的各种方法

偶尔格式化字符串时会加入tuple,我一直弱弱地这么做:

tup = (1, 2)
'tup: (%d, %d)' % (tup[0], tup[1])

或者这么做

tup = (1, 2)
'tup: %s' % str(tup)

今天搜索到 http://stackoverflow.com/questions/1455602/printing-tuple-with-string-formatting-in-python

提到了下列方法:

tup = (1, 2)
'tup: %s' % (tup,)
'tup: %s' % repr(tup)
'tup: %s' % str(tup)
'tup: {0}'.format(tup)

测了一下文中提到的和我使用的土鳖方法,python 2.7.5结果如下:

Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import timeit
>>> timeit.timeit("'%s' %((1,2),)", number=10000000)
6.564547061920166
>>> timeit.timeit("'%s' % repr((1,2))", number=10000000)
7.188735008239746
>>> timeit.timeit("'%s' % str((1,2))", number=10000000)
8.625754117965698
>>> timeit.timeit("'(%d, %d)' % (1,2)", number=10000000)
10.319281101226807
>>> timeit.timeit("'(%d, %d)' % ((1,2)[0], (1,2)[1])", number=10000000)
11.005209922790527
>>> timeit.timeit("'{0}'.format((1,2))", number=10000000)
13.548444986343384

不过在我目前使用的python 3.4.1上成功翻盘:),结果如下:

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import timeit
>>> timeit.timeit("'%s' %((1,2),)", number=10000000)
0.2406598930247128
>>> timeit.timeit("'%s' % repr((1,2))", number=10000000)
6.812374057015404
>>> timeit.timeit("'%s' % str((1,2))", number=10000000)
8.0442612930201
>>> timeit.timeit("'(%d, %d)' % (1,2)", number=10000000)
0.2473735569510609
>>> timeit.timeit("'(%d, %d)' % ((1,2)[0], (1,2)[1])", number=10000000)
0.23919461597688496
>>> timeit.timeit("'{0}'.format((1,2))", number=10000000)
12.90034785703756

所以下面的方法在python 2.7.5和python 3.4.1上都是最快的(或之一)

tup = (1, 2)
'tup: %s' % (tup,)

值得一提的是文中一位老兄说的

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:
t = 1,2,3
print ‘This is a tuple {0}’.format(t)

真的是很慢啊。


 
添加留言

Posted by on 八月 12, 2014 in Python

 

Tags: , , ,