嵌套循环比python中的flat循环快?

时间:2019-03-28 17:01:08

标签: python python-3.x performance optimization profiling

在一个related问题中,一个人想知道为什么一种方式嵌套两个循环(越长越短),而另一种嵌套越快(越长越短)。

现在,我遇到了一个比嵌套运行慢的平稳周期。怎么可能呢?

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()

enter image description here

0 个答案:

没有答案