时间循环python [英] Time a while loop python

查看:40
本文介绍了时间循环python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 while 循环内的 while 循环计时、执行所需的总时间,并记录每次循环所需的时间.如果可能的话,我需要一种方法来使用我的代码来实现这一点,或者对我可能还不知道的不同概念持开放态度.

I'm trying to time a while loop within a while loop, total time it takes to execute, and record the time it takes to do so, every time it loops. I need a way to achieve this using my code if possible, or open to different concepts I may not know of yet.

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)?

The loop will print a time, but I'm very certain it is not taking into account the nested while loop sleep time. How can I allow python to time both while loops, every loop that it will need to do (in this case 500)?

推荐答案

当您在初始循环之外设置 start 时,您可以确保获得的执行时间不正确.就像说:

When you set start outside your initial loop you are guaranteeing that you are getting the incorrect time it takes for the while loop to execute. It would be like saying:

program_starts = time.time()
while(True):
    now = time.time()
    print("It has been {0} seconds since the loop started".format(now - program_starts))

这是因为开始在整个执行时间内保持静态,而结束时间随着时间的推移稳步增加.通过在循环中放置开始时间,您可以确保您的开始时间也随着程序运行而增加.

This is because start stays static for the entire execution time while your end time is steadily increasing with the passing of time. By placing start time within the loop you ensure that your start time is also increasing as the program runs.

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)

这篇关于时间循环python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆