Python在睡觉的时候

2024-05-15 08:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在C#中,在一台基本PC上,我只需要一个简单的循环就可以了。但现在我在一个树莓皮3B+和我有一些问题。你知道吗

这是我的密码:

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秒的延迟。你知道吗

有什么建议吗? 谢谢


Tags: nametrue密码datetimeifmain时钟now
2条回答

重置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

相关问题 更多 >