Python 计时此程序在运行时的持续时间
这是整个程序,但我试图找出如何计时(天:小时:分钟:秒),如果可能的话。它是用Python编写的Python 计时此程序在运行时的持续时间,python,while-loop,Python,While Loop,这是整个程序,但我试图找出如何计时(天:小时:分钟:秒),如果可能的话。它是用Python编写的 import random x = 1 attempt = 0 while x ==1: rand1 = random.randint(1,1000) rand2 = random.randint(1,1000) attempt = attempt + 1 if rand1 ==rand2: x=2 print(rand1) print(rand2)
import random
x = 1
attempt = 0
while x ==1:
rand1 = random.randint(1,1000)
rand2 = random.randint(1,1000)
attempt = attempt + 1
if rand1 ==rand2:
x=2
print(rand1)
print(rand2)
print("Match Found.")
else:
print(rand1)
print(rand2)
print("Trying again.")
print("")
print("It took ", attempt," attempts to find a matching number.")
#for x in range(10):
# rand1 = random.randint(1,101)
# print(rand1)
# ignore the googol that's what I'm using when I figure out how to time it -> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
更好的代码:
import random
import time
from datetime import datetime
from datetime import timedelta
print('Current time: %s' % datetime. now())
attempt = 0
start_time = time.time()
while 1:
rand1 = random.randint(1,1000)
rand2 = random.randint(1,1000)
attempt += 1
if rand1 == rand2:
print(rand1)
print(rand2)
print("Match Found.", end = '\n\n')
break
else:
print(rand1)
print(rand2)
print("Trying again.", end = '\n\n')
print("It took %s attempts to find a matching number." % attempt)
print("It took %s to finish" % str(timedelta(seconds=(time.time() - start_time))))
是否有任何方法可以使其显示的时间超过秒数?我正在尝试计时一些可能长达几天的事情(如果你测试了这个程序,我正在尝试让它也这样做,但是要在一个和一个googol之间进行匹配)。如果没有,那没关系,是时候进行h*lla除法了,呵呵。编辑!这样行吗?我创建了一个函数,用于将秒转换为可能运行到天的秒数,从而确认第8行和第27行中存在错误,并且没有定义reduce。很抱歉,旧代码是针对python2的。固定的!你能检查一下吗?它成功了!非常感谢你!这非常有帮助,感谢您容忍我让您重新编辑您的添加/更改。