哪个更快-条件字符串格式设置或常规if / else?

时间:2018-07-27 04:48:02

标签: python performance string-formatting processing-efficiency

  

方法1-常规if/else

from collections import Counter

sentence = Counter(input("What would you like to say? ").lower())
sentence_length = 0

for k, v in sentence.items():
    if v > 1:
        print("There are {} {}'s in this sentence.".format(v, k))
    else:
        print("There is {} {} in this sentence.".format(v, k))
    sentence_length += v

print("There are {} words, including spaces, in total.".format(sentence_length))
  

方法2-条件字符串格式:

from collections import Counter

sentence = Counter(input("What would you like to say? ").lower())
sentence_length = 0

for k, v in sentence.items():
    print("There {} {} {}{} in this sentence.".format(("are" if v > 1 else "is"), v, k, ("'s" if v > 1 else "")))
    sentence_length += v

print("There are {} words, including spaces, in total.".format(sentence_length))

两个代码段均用于计算句子中特定字符的出现次数。两种方法之间的区别是“ for”语句内部的部分-条件字符串格式或常规if / else。我正在尝试找出哪种方法会更有效。

1 个答案:

答案 0 :(得分:0)

由于两者之间在算法上没有区别,因此回答此问题的唯一方法是对其进行测试。

当然很难对一个包含input的程序进行基准测试,因此首先我确定了键入所需句子所花的时间,然后我将其替换为一个常量赋值和一个time.sleep(7.8)

两个版本都花了不到8秒的时间。 7.8秒以外的大部分时间都花在print中。

但是,根据%timeit,版本1比版本2快了0.0005秒,加速了约0.006%。

(顺便说一下,与从str.format更改为%相比,您获得了更大的加速。)

我敢肯定,几乎所有的区别都归结于str.format的更多参数,而不是if语句和if表达式之间的区别。

但是,当然,细节可能取决于您选择的Python实现,您的版本和平台,您给它的输入字符串,以及最重要的是,输入速度如何。因此,如果这0.006%的差异实际上对某件事很重要,那么您真的需要自己进行测试。