英文:
Asyncro wait for a timer to expire in Python
问题
所以,
我来到了嵌入式编程中的C语言部分,那里有一个名为`HAL_SYSTICK_Callback`的函数,在每个时钟周期都会被执行。通过它,知道了CPU时钟,你可以像这样创建定时器:
t_1ms = 1
if(t_1ms)
t_1ms--;
然后在主代码中检查 `if(!t_1ms) 做一些事情`
现在,我想在Python中做类似的事情,在代码的某个特定点加载一个计时器,然后在代码的另一个部分检查计时器是否过期。
在执行代码时,计时器必须自行计数,而不会阻塞主代码。
我看到了像[waiting][1]这样的库,但它们似乎都是阻塞的。
[1]: https://pypi.org/project/waiting/
英文:
So,
I come to C in embedded programming where there's the function HAL_SYSTICK_Callback
which is executed on every clock tick. With it, knowing the CPU clock, you can create timers in a way like
t_1ms = 1
if(t_1ms)
t_1ms--;
And in the main code check if if(!t_1ms) do something
Now, I would like to do something like this in Python where, at a certain point in the code I load a timer and then in another part of the code, I check if the timer is exprired.
While executing the code, the timer must count by its onw without blocking the main code.
I've see libraries like waiting but they all seem blocking.
答案1
得分: 0
根据matszwecja的建议,使用time.monotonic()
对我的用例来说已经足够了。
import time
start = time.monotonic()
# 执行某些操作的代码
end = time.monotonic()
if end - start > 1:
# 检查是否花费了超过1秒的时间
# 执行其他操作
英文:
As suggest by matszwecja, the use of time.monotonic()
is more than sufficient for my use case
import time
start = time.monotonic()
# code that does something
end = time.monotonic()
if end - start > 1:
# check if more than 1 second has been spent
# do something else
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论