python - 在 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()
解决方案
通过对您的代码进行轻微修改,在每个循环中添加一个小的求和,我会延长计算时间,并且在您的核心可用容量的小波动方面,结果将更加稳定。使用这种方法,您可以清楚地看到预期的线性度。
剧情长这样
您可以看到下面使用的代码
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()
推荐阅读
- pyspark - pyspark 中的值计数花费了太多时间
- ios - 无效并重新启动后,Swift计时器将不起作用
- javascript - 循环遍历html元素中的子元素
- api - 如何在 RingCentral 沙箱中为 Outbound Fax API 创建第二个传真用户扩展?
- java - 如何制作类似于此参考的登录布局?
- postgresql - Postgres DDL 错误:'“用户”或附近的语法错误'
- laravel - 在 api 路由文件中检索标头值在 Laravel 中不起作用
- android-tv - 知道焦点在 Android TV 的最左侧视图
- python - super(subclass, class).__new__(class) 做什么?
- wordpress - How to make an input allows html tags in wordpress website