python – 嵌套while循环的运行时间
作者:互联网
要查找内部while循环的迭代次数,是否与查找内循环的运行时间相同?此外,内部循环依赖于外部循环,我知道我应该将内部while循环运行的次数乘以外部while循环以获得迭代的次数,对吧?我对如何计算while循环的迭代次数感到困惑.任何帮助,将不胜感激.谢谢!
def nested(n):
b = 1
while b <= n:
i = 1
while i < b:
print(i)
i = i*3
b += 1
感谢大家的帮助!
我想我明白答案是什么.因此,既然我们试图找到内循环迭代的次数(n-1),我还需要考虑外循环迭代内循环的次数(即n).因此,我们将迭代内循环(n-1),n次,因此如果我们使用求和符号,则给出(n(n-1))/ 2.希望这是对的.
解决方法:
你有两个问题,所以我把它们拆开了.
To find the number of iterations of the inner while loop, is it the same as finding the run time of inner loop?
不.我已经冒昧地修改你的代码,使用time.process_time测量运行时间而不受操作系统调度程序的干扰,并消除内部打印语句(I / O调用看起来很昂贵).
import time
def nested(n):
loops = list()
#Start outer timer
func_start = time.process_time()
b = 1
while b <= n:
#Start loop timer
loop_start = time.process_time()
i = 1
while i < b:
#print(i)
i = i*3
b += 1
#Finish loop timer
loop_finish = time.process_time()
loops.append(loop_finish - loop_start)
#Finish outer timer
func_finish = time.process_time()
然后我添加一个日志声明:
print("Function time: %f, Sum loop times: %f, iterations: %i, iterations by runtime: %.0f"
% (func_finish - func_start,
sum(loops),
len(loops),
(func_finish - func_start) / (sum(loops)/len(loops))) )
最后,我运行了几次.结果如下:
Function time: 0.000019, Sum loop times: 0.000010, iterations: 10, iterations by runtime: 19
Function time: 0.000135, Sum loop times: 0.000102, iterations: 100, iterations by runtime: 132
Function time: 0.001461, Sum loop times: 0.000875, iterations: 1000, iterations by runtime: 1670
Function time: 0.017174, Sum loop times: 0.011532, iterations: 10000, iterations by runtime: 14892
Function time: 0.193567, Sum loop times: 0.133996, iterations: 100000, iterations by runtime: 144457
如您所见,随着迭代次数的增加,使用相对运行时间来尝试估计迭代次数变得不那么准确.
Also since, the inner loop is dependent on on the outer loop,I know I should multiply the number of times the inner while loop runs with the outer while loop to get the number of times it is iterated, right?
这适用于理论应用.如果我在内循环中有n个指令,并且内循环运行了m次,我预测总运行时间实际上是mn.但是,您必须记住,一行代码不等于单个指令.实际上,即使某些指令在执行时间方面也不等于其他指令(例如,浮点运算与整数运算).我们在我们的定时例子中看到了这一点.
为了计算Big-O运行时边界,建议将内循环语句计数乘以循环数的技术起作用.在现实世界中,对于像Python这样的解释性语言来说,它变得更复杂,更加复杂.
标签:python,python-3-x,algorithm,big-o 来源: https://codeday.me/bug/20190828/1753102.html