简体   繁体   English

python threading.Timer如何确定经过的时间?

[英]How does python threading.Timer determine elapsed time?

I'm running some experiments in a virtual machine, which has its system time updated if its suspended. 我正在虚拟机中进行一些实验,如果该虚拟机处于暂停状态,则会更新其系统时间。 I want to know if I can suspend the virtual machine and not affect the timer. 我想知道是否可以挂起虚拟机并且不影响计时器。 That is, does Timer use system time or wall time? 也就是说,Timer使用系统时间还是墙上时间?

I've tried looking through the source code and got to _thread.lock.acquire before the code dips into C. 我尝试遍历源代码并在代码浸入C _thread.lock.acquire之前进入_thread.lock.acquire

Below is my code. 下面是我的代码。 I delegate to a subprocess that outputs 'plans'. 我委托给输出“计划”的子流程。 I keep collecting these plans until the optimal plan is found or the maximum allowed time has elapsed. 我一直在收集这些计划,直到找到最佳计划或最长允许时间过去为止。 The timer is used to terminate the process if time runs out (which is the expected state of affairs). 如果时间用完(这是预期的事务状态),则使用计时器终止进程。 I need to know that the Timer will not be effected by system time being updated as it will invalidate the experiment I'm running. 我需要知道, Timer不会受到系统时间更新的影响,因为它将使我正在运行的实验无效。

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()

Upon examination of the python source code for *unix it systems, I found that python eventually delegates to sem_timedwait from semaphore.h or pthread_cond_timedwait from pthread.h depending on support. 通过检查* unix it系统的python源代码,我发现python最终取决于支持将semaphore.h委托给sem_timedwaitpthread.h委托给了pthread_cond_timedwait Either way, both functions take a struct timespec from time.h as an absolute time to wait till -- timespec is the number of seconds and nanoseconds since the epoch. 无论哪种方式,这两个函数struct timespectime.h获取struct timespec作为等待直到的绝对时间-timespec是距该纪元以来的秒数和纳秒数。

So on the face of it seems that waiting in python is dependent on system time -- meaning my program would be effected by a change in system time. 因此,从表面上看来,在python中等待取决于系统时间-这意味着我的程序将受到系统时间变化的影响。 However, time.h specifies the constant CLOCK_MONOTONIC_RAW and the function clock_gettime , if a monotonically increasing clock is required. 但是,如果需要单调递增的时钟,则time.h指定常量CLOCK_MONOTONIC_RAW和函数clock_gettime Showing there is an ability to wait independently of system time. 显示有一种独立于系统时间进行等待的能力。 However, sadly python uses gettimeofday (marked as obsolete since 2008) which is affected by changes to system time. 但是,可悲的是,python使用的gettimeofday (自2008年以来已过时)已受到系统时间更改的影响。

In short, waiting in python on *unix systems is effected by changes to system time. 简而言之,* unix系统上的python等待会受系统时间的更改影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM