[英]How can I limit one iteration of a loop to a fixed time in seconds?
我正在尝试编程两个设备 - 第一个通过调用应用程序并手动单击程序,第二个通过调用批处理文件并等待它完成。 我需要这个循环的每次迭代为30秒,因此两个设备都可以编程。
我已经尝试记录开始迭代所花费的时间,以及编程第二个设备结束时的时间。 然后我将它设置为time.sleep(总共30次)。 这将返回每次迭代略长于30秒的执行时间。
for i in range(48):
t1 = time.time()
#program 1st board by calling app from python and clicking it using python.
#wait a static number of seconds (s) as there is no feedback from this app.
#program 2nd board by calling a batch file.
#this gives feedback as the code does not move to the next line until the
#batch file is finished
t2 = time.time()
time.sleep(30-(t2-t1))
#some other code
实际结果:超过30秒。 预期结果:正好30秒。 这是因为python中的调度吗?
这是您的操作系统中安排的结果。 当进程通过调用sleep
放弃处理器sleep
, 无法保证它会在sleep
调用中请求的经过时间后唤醒。 根据系统的繁忙程度,它可能会延迟一点,或者可能会延迟很多。
如果您有严格的时序要求,则需要实时操作系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.