python - 如何在 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。但由于模拟工作,我希望计时器计数得更快。谢谢你的回复
解决方案
这可能是由于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
...
推荐阅读
- node.js - Docker 节点容器无法启动,但在没有 docker 的情况下可以在本地工作
- jquery - 使用 jQuery 定位除 DIV 中的所有链接之外的所有链接
- android - Android studio 代码格式化问题
- python - Scrapy 没有从 Yahoo! 拉取收盘价!金融
- python - 为什么在提供它时会缺少必需的位置参数?
- android - 这里介绍sdk3.14,开启minifyEnable时构建项目失败
- windows - 将 javafx jar 打包为 mac 应用程序
- kotlin - 异步作业取消导致父取消
- amazon-web-services - docker login:存储凭据时出错“存根收到错误数据。”
- javascript - Angular8或Js阻止地址栏跳转到其他页面