I measured the runtimes of a for and a while loop in python and plotted them with matplotlib
.
To my surprise, the graphs aren't looking that linear, especially the one of the for
loop. It also took longer to loop through 600k numbers than it took to loop through 700k.
What did I do wrong or is it just python which does things differently?
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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…