我想通过比较不同的变量在Python中构建一个字符串:
+
连接(称为“plus”)%
"".join(list)
format
函数"{0.<attribute>}".format(object)
我比较了三种场景
我测量了每一次100万次的手术,平均做了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))
%
字符串格式比.format
方法快%
是一种语法符号(因此执行速度很快),而.format
至少涉及一个额外的方法调用__getattr__
我使用各种格式化方法的
timeit
运行了一个稍微好一点的分析(在Python 3.6.0上),其结果如下(用BeautifulTable打印得很漂亮)后面的
_str
&;_int
表示对各个值类型执行的操作。请注意单个变量的
concat_str
结果本质上只是字符串本身,因此不应该真正考虑它。我得出结果的准备-
我不能超过
num_vars=250
,因为一些最大参数(255)限制是timeit
。tl;dr-Python字符串格式化性能:
f-strings
是最快和更优雅的,但有时(由于某些implementation restrictions&;仅限于Py3.6+),您可能需要使用其他格式化选项。相关问题 更多 >
编程相关推荐