【问题标题】:Do if statements take significant amounts of time in python?if 语句在 python 中是否需要大量时间?
【发布时间】:2018-04-19 15:08:21
【问题描述】:

我正在创建一个绘图程序,它必须通过计算迭代值 10000-1000000 次,然后将该输出的一部分附加到列表中。为了更改它附加到哪个列表,该循环中有〜3个if语句。虽然首先使用 if 语句在逻辑上会更快,但是否节省了大量时间?

举个例子:

output = []
append_to = "pol"
for i in range(10000):
    if append_to == "pol":
        output.append(np.cos(i))
    else:
        output.append(np.sin(i))

这会明显慢于:

output = []
append_to = "pol"
if append_to == "pol":
    for i in range(10000):
        output.append(np.cos(i))
else:
    for i in range(10000):
        output.append(np.sin(i))

【问题讨论】:

  • 不管哪个更快,记住它们并不完全等价(假设append_to的值可能会改变,否则整个问题没有意义)
  • append_to 在整个循环过程中是否保持不变?在这种情况下,您可以定义f = np.cos if append_to == "pol" else np.sin,然后执行output = list(map(f, range(10000))
  • 是的,append_to 在整个循环中保持不变,为什么这会使问题无效?我问的是优化。感谢您的建议,我将不得不研究地图功能。

标签: python python-3.x for-loop if-statement optimization


【解决方案1】:

为什么不试试呢?

import numpy as np
import timeit

def one():
    output = []
    append_to = "pol"
    for i in range(10000):
        if append_to == "pol":
            output.append(np.cos(i))
        else:
            output.append(np.sin(i))

def two():
    output = []
    append_to = "pol"
    if append_to == "pol":
        for i in range(10000):
            output.append(np.cos(i))
    else:
        for i in range(10000):
            output.append(np.sin(i))

print(timeit.timeit('f()', 'from __main__ import one as f', number=1000))
print(timeit.timeit('f()', 'from __main__ import two as f', number=1000))

Output:
9.042721510999854
8.626055914000062

所以是的,正如预期的那样,它更快。只是为了让您知道查找也需要一些时间,所以如果您执行 ap = output.append 然后调用 ap 而不是 output.append 您将获得边际改进。

【讨论】:

    【解决方案2】:

    试一试!

    import math, time
    
    time_start = time.time()
    
    output = []
    append_to = "pol"
    for i in range(10000000):
        if append_to == "pol":
            output.append(math.cos(i))
        else:
            output.append(math.sin(i))
    
    print("End: " + str(time.time() - time_start))
    

    在那次跑步中,我得到了 4.278 秒。对于本次运行:

    import math, time
    
    time_start = time.time()
    
    output = []
    append_to = "pol"
    if append_to == "pol":
        for i in range(10000000):
            output.append(math.cos(i))
    else:
        for i in range(10000000):
            output.append(math.sin(i))
    
    print("End: " + str(time.time() - time_start))
    

    我得到了 3.751 秒。

    你去吧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 2013-05-12
      • 1970-01-01
      • 2020-10-02
      • 2015-06-24
      相关资源
      最近更新 更多