我想比较不同,从不同的变量建立在Python的字符串:使用+
来连接Python字符串格式化:'%'比'格式'功能更有效吗?
- (简称 '加号')使用
format
使用"".join(list)
- 使用
%
- 功能
- 使用
"{0.<attribute>}".format(object)
我为3种类型的scenari的
- 串与2个变量 相比
- 串有4个变量
- 串有4个变量,每个变量使用两次
予测得的各1个百万次操作时间和平均执行6个措施。我想出了以下时序:
在每一个场景,我想出了以下结论
- 级联似乎是格式化使用
%
是最快的方法 - 之一比用
format
函数格式化快得多
我认为format
比%
(例如在this question)和%
几乎被弃用。
因此我几个问题:
- 是
%
真的比format
快? - 如果是这样,为什么呢?
- 为什么
"{} {}".format(var1, var2)
比"{0.attribute1} {0.attribute2}".format(object)
更高效?
作为参考,我用下面的代码来测量不同的定时。
import time
def timing(f, n, show, *args):
if show: print f.__name__ + ":\t",
r = range(n/10)
t1 = time.clock()
for i in r:
f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args); f(*args)
t2 = time.clock()
timing = round(t2-t1, 3)
if show: print timing
return timing
#Class
class values(object):
def __init__(self, a, b, c="", d=""):
self.a = a
self.b = b
self.c = c
self.d = d
def test_plus(a, b):
return a + "-" + b
def test_percent(a, b):
return "%s-%s" % (a, b)
def test_join(a, b):
return ''.join([a, '-', b])
def test_format(a, b):
return "{}-{}".format(a, b)
def test_formatC(val):
return "{0.a}-{0.b}".format(val)
def test_plus_long(a, b, c, d):
return a + "-" + b + "-" + c + "-" + d
def test_percent_long(a, b, c, d):
return "%s-%s-%s-%s" % (a, b, c, d)
def test_join_long(a, b, c, d):
return ''.join([a, '-', b, '-', c, '-', d])
def test_format_long(a, b, c, d):
return "{0}-{1}-{2}-{3}".format(a, b, c, d)
def test_formatC_long(val):
return "{0.a}-{0.b}-{0.c}-{0.d}".format(val)
def test_plus_long2(a, b, c, d):
return a + "-" + b + "-" + c + "-" + d + "-" + a + "-" + b + "-" + c + "-" + d
def test_percent_long2(a, b, c, d):
return "%s-%s-%s-%s-%s-%s-%s-%s" % (a, b, c, d, a, b, c, d)
def test_join_long2(a, b, c, d):
return ''.join([a, '-', b, '-', c, '-', d, '-', a, '-', b, '-', c, '-', d])
def test_format_long2(a, b, c, d):
return "{0}-{1}-{2}-{3}-{0}-{1}-{2}-{3}".format(a, b, c, d)
def test_formatC_long2(val):
return "{0.a}-{0.b}-{0.c}-{0.d}-{0.a}-{0.b}-{0.c}-{0.d}".format(val)
def test_plus_superlong(lst):
string = ""
for i in lst:
string += str(i)
return string
def test_join_superlong(lst):
return "".join([str(i) for i in lst])
def mean(numbers):
return float(sum(numbers))/max(len(numbers), 1)
nb_times = int(1e6)
n = xrange(5)
lst_numbers = xrange(1000)
from collections import defaultdict
metrics = defaultdict(list)
list_functions = [
test_plus, test_percent, test_join, test_format, test_formatC,
test_plus_long, test_percent_long, test_join_long, test_format_long, test_formatC_long,
test_plus_long2, test_percent_long2, test_join_long2, test_format_long2, test_formatC_long2,
# test_plus_superlong, test_join_superlong,
]
val = values("123", "456", "789", "0ab")
for i in n:
for f in list_functions:
print ".",
name = f.__name__
if "formatC" in name:
t = timing(f, nb_times, False, val)
elif '_long' in name:
t = timing(f, nb_times, False, "123", "456", "789", "0ab")
elif '_superlong' in name:
t = timing(f, nb_times, False, lst_numbers)
else:
t = timing(f, nb_times, False, "123", "456")
metrics[name].append(t)
#Get Average
print "\n===AVERAGE OF TIMINGS==="
for f in list_functions:
name = f.__name__
timings = metrics[name]
print "{:>20}:\t{:0.5f}".format(name, mean(timings))
使用'timeit'代替你的自定义函数,可能第一次执行速度慢,但后续函数执行速度更快,但实际上你只能调用一次函数。 https://docs.python.org/2/library/timeit.html –
正如@MaximilianPeters所说,你应该使用'timeit'来获得值得信赖的结果 –
谢谢你们。我检查了'timeit',但我应该一直很高,因为我相信它只支持Python 3.x,我主要使用2.7。 –