首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python3 time.sleep()行为反常

Python3 time.sleep()行为反常
EN

Stack Overflow用户
提问于 2020-06-25 11:51:38
回答 1查看 41关注 0票数 0

L.S,

我正在尝试学习python(3),并且对time.sleep()的行为感到困惑,我在rpi3b上运行raspbian。

代码语言:javascript
复制
#!/usr/bin/python3
import bluetooth
import sys
import time
_shuttermac ="11:22:33:44:5D:6A"
while True:
    # check if the device is switched on by mac address lookup
    print("Checking " + time.strftime("%a, %d %b %Y %H:%M:%S - ", time.gmtime()),end ="")
    result = bluetooth.lookup_name(_shuttermac, timeout=5)
    #print(result)
    if (result != None):
        print("Device detected by bluetooth mac lookup")
    else:
        print("Device with MAC " + _shuttermac + " NOT detected")
    time.sleep(1)   # check every 5 secs if device comes online      
sys.exit()

输出

代码语言:javascript
复制
Checking Thu, 25 Jun 2020 11:21:02 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:08 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:14 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:20 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:26 - Device with MAC 11:22:33:44:5D:6A NOT detected

如您所见,输出语句间隔为6秒,而不是编码的1

我哪里出错了?

EN

回答 1

Stack Overflow用户

发布于 2020-06-25 12:09:00

6秒间隔是因为当查找失败时,while True的每个循环都会执行两个耗时的操作:

  1. bluetooth.lookup_name(_shuttermac, timeout=5)有5秒的超时时间。如果快速找到它,它应该完成faster
  2. time.sleep(1)暂停整个Python程序1秒的

您可以缩短bluetooth.lookup_name的超时时间和sleep()持续时间。这可能会给查找的准确性带来意想不到的后果(我对它不太熟悉)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62574671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档