首页 > 解决方案 > 如何在 Python 中为 0.1 步构建计时器

问题描述

我使用以下代码为 Python 中的模拟构建计时器。通常计时器在几秒钟内运行,但由于模拟研究,我希望程序更快并在十分之一秒内运行。(为此,在代码中添加了 *10)

startTime = time.time()*10
while True:
    currentTimeOfSimulation = np.round(time.time()*10 - startTime, 1)
    print('current time', currentTimeOfSimulation)

我得到以下输出:

...
current time = 0.0
current time = 0.0
current time = 0.2
current time = 0.2
...
current time = 0.3
current time = 0.3
current time = 0.5
current time = 0.5

如您所见,步骤 0.1、0.4、0.7 被跳过。似乎每次运行都会跳过相同的数字。为什么会这样?

编辑:计时器应以 0.1 步从 0.0 计数到 1,持续时间为 0.1 秒。或者换句话说,在一秒钟内,时间应该以 0.1 的步长从 0.0 计数到 10。我确实实现了一个计时器,它需要 1 秒才能从 0.0 计数到 0.1 中的 1。但由于模拟工作,我希望计时器计数得更快。谢谢你的回复

标签: pythontimerroundingclock

解决方案


这可能是由于np.round(). 但请注意,您不需要为此使用numpy,Python 有一个内置round()函数:

import time

start_time = time.time()
while True:
    current_time_of_simulation = round((time.time() - start_time)/10, 1)
    print('current time', current_time_of_simulation)

输出:

current time 0.0
...
current time 0.1
...
current time 0.2
...
current time 0.3
...
current time 0.4
...
current time 0.5
...
current time 0.6
...

推荐阅读