我正在尝试在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同时循环,循环,它需要做的每个循环(在这种情况下是500)?
最佳答案
当您在初始循环之外设置start时,您可以保证获得while循环执行所需的时间不正确.这就像说:
原文链接:https://www.f2er.com/python/439629.htmlprogram_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 "," seconds")
print(random_number)
printerLooper = False
end_time = time.time()
print("total time taken this loop: ",end_time - start_time)