首页 > 解决方案 > 在 python 中,for 和 while 循环都不是在线性时间 O(n) 中运行

问题描述

我在 python 中测量了 for 和 while 循环的运行时间,并用matplotlib. 令我惊讶的是,这些图表看起来并不是那么线性,尤其是for循环中的一个。循环 60 万个数字所花费的时间也比循环 70 万个数字所花费的时间更长。

我做错了什么还是只是 python 做的事情不同?

import time
import matplotlib.pyplot as plt

time_while=[]
time_for=[]
for i in range(200000, 1000000+1, 100000):
    t1 = time.time()
    n = 0
    while n < i:
        n += 1
    t2 = time.time()
    time_while.append(round(t2-t1,5))

    t1 = time.time()
    for n in range(i):
       n=n
    t2 = time.time()
    time_for.append(round(t2-t1,5))

x=["200k","300k","400k","500k","600k","700k","800k","900k","1Mio",]
plt.plot(x, time_while,label="while")
plt.plot(x, time_for,label="for")
plt.legend()
plt.show()

在此处输入图像描述

标签: pythonloopsfor-loopwhile-loopruntime

解决方案


通过对您的代码进行轻微修改,在每个循环中添加一个小的求和,我会延长计算时间,并且在您的核心可用容量的小波动方面,结果将更加稳定。使用这种方法,您可以清楚地看到预期的线性度。

剧情长这样

循环比较

您可以看到下面使用的代码

import time
import matplotlib.pyplot as plt

time_while=[]
time_for=[]
for i in range(200000, 1000000+1, 100000):
    t1 = time.time()
    n = 0
    while n < i:
        sum(k for k in range(10))
        n += 1
    t2 = time.time()
    time_while.append(round(t2-t1,5))

    t1 = time.time()
    for n in range(i):
        sum(k for k in range(10))
        n=n
    t2 = time.time()
    time_for.append(round(t2-t1,5))

x=["200k","300k","400k","500k","600k","700k","800k","900k","1Mio",]
plt.plot(x, time_while,label="while")
plt.plot(x, time_for,label="for")
plt.legend()
plt.show()

推荐阅读