Python字符串格式:'%'比'format'函数效率更高?

Jea*_* T. 29 python performance

我想比较不同以在Python中用不同的变量构建一个字符串:

  • 使用+来连接(被称为"加号")
  • 运用 %
  • 运用 "".join(list)
  • 使用format功能
  • 运用 "{0.<attribute>}".format(object)

我比较了3种类型的情景

  • 带2个变量的字符串
  • 4个变量的字符串
  • 带有4个变量的字符串,每个变量两次使

我每次测量100万次操作并且平均执行超过6次测量.我想出了以下时间:

计时

在每个场景中,我得出以下结论

  • 连接似乎是最快的方法之一
  • 使用格式化%比使用format函数格式化要快得多

我相信format%(例如在这个问题中)要好得多,并且%几乎被弃用了.

因此,我有几个问题:

  1. %真的比快format
  2. 如果是这样,为什么呢?
  3. 为什么"{} {}".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))
Run Code Online (Sandbox Code Playgroud)

sha*_*k3r 24

  1. 是的,%字符串格式化比.format方法更快
  2. 最有可能(这可能有一个更好的解释),因为它%是一个语法符号(因此快速执行),而.format涉及至少一个额外的方法调用
  3. 因为属性值访问还涉及额外的方法调用,即. __getattr__

我使用timeit各种格式化方法运行了一个稍微好一点的分析(在Python 3.6.0上),结果如下(漂亮地用BeautifulTable打印) -

+-----------------+-------+-------+-------+-------+-------+--------+
| Type \ num_vars |   1   |   2   |   5   |  10   |  50   |  250   |
+-----------------+-------+-------+-------+-------+-------+--------+
|    f_str_str    | 0.306 | 0.064 | 0.106 | 0.183 | 0.737 | 3.422  |
+-----------------+-------+-------+-------+-------+-------+--------+
|    f_str_int    | 0.295 | 0.174 | 0.385 | 0.686 | 3.378 | 16.399 |
+-----------------+-------+-------+-------+-------+-------+--------+
|   concat_str    | 0.012 | 0.053 | 0.156 | 0.31  | 1.707 | 16.762 |
+-----------------+-------+-------+-------+-------+-------+--------+
|    pct_s_str    | 0.056 | 0.178 | 0.275 | 0.469 | 1.872 | 9.191  |
+-----------------+-------+-------+-------+-------+-------+--------+
|    pct_s_int    | 0.128 | 0.208 | 0.343 | 0.605 | 2.483 | 13.24  |
+-----------------+-------+-------+-------+-------+-------+--------+
| dot_format_str  | 0.418 | 0.217 | 0.343 | 0.58  | 2.241 | 11.163 |
+-----------------+-------+-------+-------+-------+-------+--------+
| dot_format_int  | 0.416 | 0.277 | 0.476 | 0.811 | 3.378 | 17.829 |
+-----------------+-------+-------+-------+-------+-------+--------+
| dot_format2_str | 0.433 | 0.242 | 0.416 | 0.675 | 3.152 | 16.783 |
+-----------------+-------+-------+-------+-------+-------+--------+
| dot_format2_int | 0.428 | 0.298 | 0.541 | 0.933 | 4.444 | 24.767 |
+-----------------+-------+-------+-------+-------+-------+--------+

跟踪_str_int表示操作是在各自的值类型上执行的.

请注意,concat_str单个变量的结果基本上只是字符串本身,所以不应该考虑它.

我得到的结果 -

from timeit import timeit
from beautifultable import BeautifulTable  # pip install beautifultable

times = {}

for num_vars in (1, 2, 5, 10, 50, 250):
    f_str = "f'{" + '}{'.join([f'x{i}' for i in range(num_vars)]) + "}'"
    # "f'{x0}{x1}"
    concat = '+'.join([f'x{i}' for i in range(num_vars)])
    # 'x0+x1'
    pct_s = '"' + '%s'*num_vars + '" % (' + ','.join([f'x{i}' for i in range(num_vars)]) + ')'
    # '"%s%s" % (x0,x1)'
    dot_format = '"' + '{}'*num_vars + '".format(' + ','.join([f'x{i}' for i in range(num_vars)]) + ')'
    # '"{}{}".format(x0,x1)'
    dot_format2 = '"{' + '}{'.join([f'{i}' for i in range(num_vars)]) + '}".format(' + ','.join([f'x{i}' for i in range(num_vars)]) + ')'
    # '"{0}{1}".format(x0,x1)'

    vars = ','.join([f'x{i}' for i in range(num_vars)])
    vals_str = tuple(map(str, range(num_vars)))
    setup_str = f'{vars} = {vals_str}'
    # "x0,x1 = ('0', '1')"
    vals_int = tuple(range(num_vars))
    setup_int = f'{vars} = {vals_int}'
    # 'x0,x1 = (0, 1)'

    times[num_vars] = {
        'f_str_str': timeit(f_str, setup_str),
        'f_str_int': timeit(f_str, setup_int),
        'concat_str': timeit(concat, setup_str),
        # 'concat_int': timeit(concat, setup_int), # this will be summation, not concat
        'pct_s_str': timeit(pct_s, setup_str),
        'pct_s_int': timeit(pct_s, setup_int),
        'dot_format_str': timeit(dot_format, setup_str),
        'dot_format_int': timeit(dot_format, setup_int),
        'dot_format2_str': timeit(dot_format2, setup_str),
        'dot_format2_int': timeit(dot_format2, setup_int),
    }

table = BeautifulTable()
table.column_headers = ['Type \ num_vars'] + list(map(str, times.keys()))
# Order is preserved, so I didn't worry much
for key in ('f_str_str', 'f_str_int', 'concat_str', 'pct_s_str', 'pct_s_int', 'dot_format_str', 'dot_format_int', 'dot_format2_str', 'dot_format2_int'):
    table.append_row([key] + [times[num_vars][key] for num_vars in (1, 2, 5, 10, 50, 250)])
print(table)
Run Code Online (Sandbox Code Playgroud)

我无法超越num_vars=250因为一些最大参数(255)的限制timeit.

tl; dr - Python字符串格式化性能:f-strings最快且更优雅,但有时​​(由于某些实现限制和仅限Py3.6 +),您可能必须使用其他格式化选项.

  • Python:可以构建字符串以对构建字符串的各种方法进行时序测试,然后导入一个外部库,该外部库使用自己的__str__`来构建自定义对象,该自定义对象可以构建字符串(并且很可能构建该字符串)排除所有在时序测试中产生的结果的字符串。 (2认同)