首页 > 解决方案 > python中的嵌套循环比平面快吗?

问题描述

在一个相关问题中,有人想知道为什么以一种方式嵌套两个周期(更长更短)另一种更快(更短更长)。

现在我遇到了一个比嵌套慢的扁平循环。怎么会这样?

from time import perf_counter as clock
import matplotlib.pyplot as plt

def long_short():
    start = clock()
    counter = 0
    for i in range(100):
        for j in range(10):
            counter += 1
    return (clock() - start)*1e6

def short_long():
    start = clock()
    counter = 0
    for i in range(10):
        for j in range(100):
            counter += 1
    return (clock() - start)*1e6

def single():
    start = clock()
    counter = 0
    for i in range(1000):
        counter += 1
    return (clock() - start)*1e6

y1, y2, y3 = [], [], []
for i in range(30):
    y1.append(long_short())
    y2.append(short_long())
    y3.append(single())

plt.figure()
ax1 = plt.plot(y1, c="b", label="Longer loop over shorter")
ax2 = plt.plot(y2, c="g", label="Shorter loop over longer")
ax3 = plt.plot(y3, c="r", label="Single loop")
plt.xlabel("n", fontsize=16)
plt.ylabel("Time (us)", fontsize=16)
plt.legend(loc=2, fontsize=14)
plt.show()

在此处输入图像描述

标签: pythonpython-3.xperformanceoptimizationprofiling

解决方案


推荐阅读