【问题标题】:Why f-strings are slow compared to % notation?为什么 f-strings 比 % 表示法慢?
【发布时间】:2023-02-10 02:44:22
【问题描述】:

我一直认为 f 字符串比其他字符串格式化方式更快。

最近我做了一个小研究。结果令人惊讶——使用 f 字符串的小代码比使用百分比表示法花费更多的时间。有人可以解释原因吗?

代码如下:

from time import perf_counter_ns

i = 1.34234324

begin = perf_counter_ns()
s = f'{i} {i}'
end = perf_counter_ns()
print(end - begin)


begin = perf_counter_ns()
s = '%f %f' % (i, i)
end = perf_counter_ns()
print(end - begin)

打印结果是:

4300
2000

我使用 Python 3.10.7

我预计 f 弦会有更好的性能。

我也想得到答案,将 float 替换为字符串的方式是禁食。

【问题讨论】:

  • 为什么你会期望不同的结果?一个样本以什么方式足以证明任何事情?
  • 他们真的给你相同的结果吗?
  • 如果您使用%,然后使用 fstring,则两种变体都同样快(有时一个更快,有时另一个更快)。这不是一个可靠的基准测试方法
  • 请在您的问题中使用this code
  • @knittl 试试我的。

标签: python string performance formatting cpython


【解决方案1】:

内部必须进行一些缓存。看看如果我们交换处理顺序会发生什么:

from time import perf_counter_ns

i = 1.34234324

begin = perf_counter_ns()
s = '%f %f' % (i, i)
end = perf_counter_ns()
print(end - begin)

begin = perf_counter_ns()
s = f'{i} {i}'
end = perf_counter_ns()
print(end - begin)

输出:

11098
8145

结论:

这不是一个好的测试

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2017-08-24
    • 2018-12-31
    • 2020-02-24
    • 1970-01-01
    • 2011-03-23
    相关资源
    最近更新 更多