用于模拟的秒表计时器

stopwatch timer for a simulation

我想将初始时间设置为零(0 秒)并执行某些操作直到 运行 持续时间结束(比如 3600 秒)

此程序用于模拟,我认为我不能简单地使用计数器,因为在模拟 运行ning 时会发生其他过程。

例如

start = 0
run_time = 3600
timer = 0
while timer <= run_time:
    print(timer)
    # do other stuff

试试这个:

from time import time

print("Stopwatch running..")
t0 = time()
watch = 0

while watch-t0 < 3:
    watch = time()
    # Your Code

print(" Finished!\n Time =",watch - t0)

您可以简单地使用 datetime 模块:

import datetime as dt

start = dt.datetime.now()
run_time = dt.timedelta(seconds=3600)

while dt.datetime.now() <= start + run_time:
   ....
   ....

我明白你的意思了,你可以使用线程来完成这个

from threading import Thread
from time import sleep

run_time = 10 #seconds

def WhateverYourDoing():
    while run:
        print("Look, I'm doing stuff!")
        sleep(1)

sim = Thread(target=WhateverYourDoing)

for x in range(3, 0, -1):
    print(x)
    sleep(1)
print("Go!")
run = True
sim.start()
sleep(run_time)
run = False
print("DONE")