Python如何计算while循环的时间

21

我正在尝试计时一个while循环中的另一个while循环,记录它执行所需的总时间,并在每次循环时记录所需的时间。如果可能,我需要找到一种使用我的代码实现这一目标的方法,或者接受我还不知道的不同概念。

import random
import time
import sys

def main():


    looperCPU = 500
    start = time.time()
    while (looperCPU != 0):
        #start = time.time()

        #this is the computation for 3 secs
        time.sleep(3)
        random_number = random.randint(0,1000)

        #Send to printer for processing
        #.75 secs to 4.75 secs to generate a pause before printing
        secondsPause = random.uniform(.75,4.75)


        #This is the printer function
        printerLooper = True
        while printerLooper == True :
            print("Sleeping for ", secondsPause, " seconds")
            print(random_number)
            printerLooper = False


        #
        print("total time taken this loop: ", time.time() - start)
        looperCPU -= 1    



main()

这个循环将会打印时间,但是我非常确定它没有考虑到嵌套的while循环的睡眠时间。我该如何让Python计时两个while循环,每个循环都需要执行(在这种情况下是500次)?


请问如何获取 Python 程序的执行时间? - Greg
@greg 如果你看了我的代码,我正在做计时模块。我试图弄清楚的比整个程序的基本计时更深入。它必须为每个循环计时。 - Bain
2
你的嵌套循环实际上并不是一个循环...循环体将始终只被执行一次。此外,你打印了你要睡 secondsPause ,但你实际上从未这样做。 - Gordon Bailey
tqdm包可用于Python中的循环。请参考此相关SO讨论 - KarthikS
4个回答

28

如果你在初始循环之外设置开始时间,那么你保证得到的是 while 循环执行时间不正确。这就像说:

program_starts = time.time()
while(True):
    now = time.time()
    print("It has been {0} seconds since the loop started".format(now - program_starts))
这是因为起始时间在整个执行过程中保持不变,而结束时间随着时间的推移而稳步增加。通过将起始时间放置在循环内部,您可以确保程序运行时起始时间也在增加。
因为开始时间在整个执行期间保持静态,而你的结束时间则随时间的推移而稳步增加。通过将开始时间放在循环内,你可以确保程序运行时开始时间也在增加。
while (looperCPU != 0):
    start_time = time.time()
    # Do some stuff
    while printerLooper == True :
        print("Sleeping for ", secondsPause, " seconds")
        print(random_number)
        printerLooper = False
    end_time = time.time()

    print("total time taken this loop: ", end_time - start_time)

太棒了,这正是我所需要的。不知何故我的时间安排混乱了。感谢您提出这个概念。 - Bain

3

在Python中,您可以查看此文档https://docs.python.org/2/library/timeit.html
Stackoverflow示例:如何使用timeit模块

import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

在Jupyter笔记本中,
%%timeit -n 100
import pandas as pd
s = pd.Series([101.00, 121.00])
summary = 0
for item in s:
    summary+=item

1
你可以使用这个pytictoc。使用pip或conda进行安装。在pytictoc上阅读文档。它的工作方式类似于matlab的tic toc。基本上只需用tic启动计时器,然后用toc结束。然后你可以直接打印或将其存储在一个新变量中。
from pytictoc import TicToc
def main()
    t = TicToc()  # create instance of class
    start_time= t.tic() #start timer
    while ():  


    #end of while loop

    end_time = t.toc()
    print("end_time", end_time)

2
请在您的回答中添加一些文字来解释它。仅有代码是没有帮助的。 - buhtz

1

想法正确,但你的计时函数放置有点偏差,我在这里进行了更正:

import random
import time import sys

def main():

    looperCPU = 500
    start = time.time()
    while (looperCPU != 0):
       #this is the computation for 3 secs
       time.sleep(3)
       random_number = random.randint(0,1000)

       #Send to printer for processing
       #.75 secs to 4.75 secs to generate a pause before printing
       secondsPause = random.uniform(.75,4.75)


       #This is the printer function
       printerLooper = True
       myStart = time.time()
       while printerLooper == True :
          print("Sleeping for ", secondsPause, " seconds")
          print(random_number)
          printerLooper = False
          print("total time taken this loop: ", time.time() - myStart)    

       looperCPU -= 1    
main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接