python - python threading.Timer 如何确定耗时?

标签 python timer python-3.4

我正在虚拟机中运行一些实验,如果虚拟机挂起,系统时间就会更新。我想知道是否可以暂停虚拟机而不影响计时器。即Timer使用的是系统时间还是wall时间?

我尝试查看源代码,并在代码深入 C 语言之前找到了 _thread.lock.acquire

下面是我的代码。我委托(delegate)给一个输出“计划”的子流程。我不断收集这些计划,直到找到最佳计划或已过最大允许时间。计时器用于在时间耗尽时终止进程(这是事务的预期状态)。我需要知道计时器不会受到系统时间更新的影响,因为它会使我正在运行的实验无效。

p = Popen(args, stdout=PIPE, cwd=self.working_directory)
timer = Timer(float(self.planning_time), p.terminate)
timer.start()

plan = None
while True:
    try:
        plan = list(decode_plan_from_optic(self.decode(p.stdout), 
                    report_incomplete_plan=True))
    except IncompletePlanException:
        break
timer.cancel()

最佳答案

在检查 *unix it 系统的 python 源代码后,我发现 python 最终委托(delegate)给 sem_timedwait来自semaphore.hpthread_cond_timedwait来自pthread.h取决于支持。无论哪种方式,这两个函数都采用 struct timespec来自time.h作为等待的绝对时间 -- timespec 是自纪元以来的秒数和纳秒数。

所以从表面上看,Python 中的等待似乎依赖于系统时间——这意味着我的程序会受到系统时间变化的影响。然而,time.h指定常量CLOCK_MONOTONIC_RAW和函数 clock_gettime ,如果需要单调递增的时钟。表明有能力独立于系统时间进行等待。然而,遗憾的是 python 使用 gettimeofday (自 2008 年起标记为过时)受系统时间更改的影响。

简而言之,*unix 系统上的 python 中的等待受到系统时间更改的影响。

关于python - python threading.Timer 如何确定耗时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24849352/

相关文章:

python - 数据描述符和非数据描述符的正确定义哪一个?

python - 如何使用Prometheus 存储Data 以供Grafana 可视化

python - Tensorboard 未在 Windows 上填充图形

bash - 仅在用户输入期间运行的计时器

python - 捕获标准输出时 python2 和 python3 之间的 StringIO 可移植性

python - 是否可以在未安装 Python 3.4 的情况下使用 pyvenv-3.4?

python - 字符串如何在python中转换为int?

python - 为什么 globals() 在迭代期间改变大小?

java - 获取 TimerTask 下次计划运行的时间

timer - 如何创建基于时间的 Flutter 应用程序?