python 想睡几秒钟

python while going to sleep for some seconds

我是一个相当新的 Python 程序员,即使我是 C# 的老程序员,我正在尝试开发一个实时时钟,它将用于显示一个简单的秒表。

在基本 PC 上的 C# 中,我只需要一个简单的循环就可以了。但现在我的成绩是 Raspberry Pi 3 B+,我遇到了一些问题。

这是我的代码:

if __name__ == '__main__':

    try:
        while True:
            now = datetime.datetime.now()
            if now.second != datetime.datetime.now().second:
                print(now)
                time.sleep(0.1)
    except KeyboardInterrupt:
        pass

预期的输出是每秒换行,但事实并非如此:

2019-02-09 19:33:56.999996
2019-02-09 19:33:57.999999
2019-02-09 19:33:58.999998
2019-02-09 19:34:00.999989
2019-02-09 19:34:01.999999
2019-02-09 19:34:02.999999
2019-02-09 19:34:03.999994
2019-02-09 19:34:07.999989
2019-02-09 19:34:08.999998
2019-02-09 19:34:11.999993
2019-02-09 19:34:12.999993
2019-02-09 19:34:13.999993

正如您在 19.34.58 所见,它似乎要休眠一秒钟,而在 19.34.08 则休眠 3 秒钟。

有什么办法可以避免这种情况吗?

如果我尝试拦截 GPIO 中断,问题会更加明显:事件的时间戳有时会有 2 或 3 秒的延迟。

有什么建议吗? 谢谢

您重置 now 太频繁了:

while True:
    now = datetime.datetime.now()
    while True: # keep the 'now' until one second ticked by:
        if now.second != datetime.datetime.now().second:
            print(now)
            time.sleep(0.1)
        else:
            break # get the next now ...

你能得到任何输出都是运气....第二个必须在

之间的时间跨度内打勾
now = datetime.datetime.now()                       # this line
if now.second != datetime.datetime.now().second:    # and this line

以下几行...

now = datetime.datetime.now()
if now.second != datetime.datetime.now().second:
    print(now)

... 仅当对 datetime.datetime.now() 的两次连续调用未在同一秒内到达时才会打印 now

正如您的输出所示,如果第二个增量没有落在这两个调用之间,这有时会失败。

同步计数器

可以这样构建一个与datetime保持同步的计数器。

import datetime
import time

precision = 0.1

previous = datetime.datetime.now()
while True:
    now = datetime.datetime.now()
    if previous.second != now.second:
        print(now)
        previous = now
    time.sleep(precision)

输出

2019-02-09 14:32:13.070108
2019-02-09 14:32:14.001819
2019-02-09 14:32:15.033610
2019-02-09 14:32:16.065388
2019-02-09 14:32:17.089926
2019-02-09 14:32:18.021687
2019-02-09 14:32:19.053557