计算中间表达式时,Python 嵌套循环速度比较意外变慢

标签 python algorithm timing

在python执行的操作较多的情况下,速度较慢。

以下是两个独立嵌套循环的非常简单的比较(用于查找合计为 1000 的毕达哥拉斯三元组 (a,b,c)):

#Takes 9 Seconds
for a in range(1, 1000):
  for b in range(a, 1000):
    ab = 1000 - (a + b)
    for c in range(ab, 1000):
      if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))):
        print(a,b,c)
        exit()


#Solution B
#Takes 7 Seconds
for a in range(1, 1000):
  for b in range(a, 1000):
    for c in range(b, 1000):
      if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))):
        print(a,b,c)
        exit()

我希望解决方案 A 比解决方案 B 少一两秒,但它反而增加了完成所需的时间。两秒。

instead of iterating
1, 1, 1
1, 1, 2
...
1, 1, 999
1, 2, 2

It would iterate
1, 1, 998
1, 1, 999
1, 2, 997
1, 2, 998
1, 2, 999
1, 3, 996

在我看来,解决方案 a 应该通过减少数千到数百万次操作来大大提高速度,但实际上并没有。

我知道有一种简单的方法可以大大改进这个算法,但我试图理解为什么 python 在看起来更快的情况下运行得更慢。

最佳答案

您可以只计算每个解决方案中的迭代总数,并看到 A 需要更多迭代才能找到结果:

#Takes 9 Seconds
def A():
 count = 0
 for a in range(1, 1000):
  for b in range(a, 1000):
    ab = 1000 - (a + b)
    for c in range(ab, 1000):
      count += 1
      if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))):
        print(a,b,c)
        print('A:', count)
        return


#Solution B
#Takes 7 Seconds
def B():
 count = 0
 for a in range(1, 1000):
  for b in range(a, 1000):
    for c in range(b, 1000):
      count += 1
      if(((a + b + c) == 1000) and ((a**2) + (b**2) == (c**2))):
        print(a,b,c)
        print('B:', count)
        return

A()
B()

输出:

A: 115425626
B: 81137726

这就是 A 较慢的原因。 ab = 1000 - (a + b) 也需要时间。

关于计算中间表达式时,Python 嵌套循环速度比较意外变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56120774/

相关文章:

c++ - 如何正确计时 MPI 代码

python - Django 错误 : render_to_response() got an unexpected keyword argument 'context_instance'

python - 如何警告我潜在的 NameError?

python - 使用 NumPy argsort 并接收二维数组

python - 在python中递归打印钻石

algorithm - 了解速度并实现 Boids 算法?

algorithm - 仅使用可以对 n 个数字进行排序的函数对 n^2 个数字进行排序

java - 如何计算忽略等待其他线程的时间的程序

linux - 如何在不降低设备速度的情况下调试 gstreamer

c++ - 链表中元素的成对交换(通过改变指针)