事件调度 单调时钟的值(以小数秒为单位),即不能倒退的时钟。时钟不受系统时钟更新的影响


time — Time access and conversions — Python 3.8.5 documentation https://docs.python.org/3/library/time.html#time.monotonic

PEP 418 -- Add monotonic time, performance counter, and process time functions | Python.org https://www.python.org/dev/peps/pep-0418/

If a program uses the system time to schedule events or to implement a timeout, it may fail to run events at the right moment or stop the timeout too early or too late when the system time is changed manually or adjusted automatically by NTP. A monotonic clock should be used instead to not be affected by system time updates: time.monotonic().

To measure the performance of a function, time.clock() can be used but it is very different on Windows and on Unix. On Windows, time.clock() includes time elapsed during sleep, whereas it does not on Unix. time.clock() resolution is very good on Windows, but very bad on Unix. The new time.perf_counter() function should be used instead to always get the most precise performance counter with a portable behaviour (ex: include time spend during sleep).

Until now, Python did not provide directly a portable function to measure CPU time. time.clock() can be used on Unix, but it has bad resolution. resource.getrusage() or os.times() can also be used on Unix, but they require to compute the sum of time spent in kernel space and user space. The new time.process_time() function acts as a portable counter that always measures CPU time (excluding time elapsed during sleep) and has the best available resolution.

Each operating system implements clocks and performance counters differently, and it is useful to know exactly which function is used and some properties of the clock like its resolution. The new time.get_clock_info() function gives access to all available information about each Python time function.

time.monotonic() → float

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.

Changed in version 3.5: The function is now always available and always system-wide.

time.monotonic_ns() → int

Similar to monotonic(), but return time as nanoseconds.

New in version 3.7.

time.perf_counter() → float

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.

time.perf_counter_ns() → int

Similar to perf_counter(), but return time as nanoseconds.

New in version 3.7.

time.process_time() → float

Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.

time.process_time_ns() → int

Similar to process_time() but return time as nanoseconds.

New in version 3.7.

time.sleep(secs)

Suspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

Changed in version 3.5: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).

time.monotonic() → float

返回单调时钟的值(以小数秒为单位),即不能倒退的时钟。时钟不受系统时钟更新的影响。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。

3.3 新版功能.

在 3.5 版更改: 该功能现在始终可用且始终在系统范围内。

time.monotonic_ns() → int

与 monotonic() 相似,但是返回时间为纳秒数。

3.7 新版功能.

time.perf_counter() → float

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间。它确实包括睡眠期间经过的时间,并且是系统范围的。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。

3.3 新版功能.

time.perf_counter_ns() → int

与 perf_counter() 相似,但是返回时间为纳秒。

3.7 新版功能.

time.process_time() → float

返回当前进程的系统和用户CPU时间总和的值(以小数秒为单位)。它不包括睡眠期间经过的时间。根据定义,它在整个进程范围中。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。

3.3 新版功能.

time.process_time_ns() → int

与 process_time() 相似,但是返回时间为纳秒。

3.7 新版功能.

time.sleep(secs)

暂停执行调用线程达到给定的秒数。参数可以是浮点数,以指示更精确的睡眠时间。实际的暂停时间可能小于请求的时间,因为任何捕获的信号将在执行该信号的捕获例程后终止 sleep() 。此外,由于系统中其他活动的安排,暂停时间可能比请求的时间长任意量。

在 3.5 版更改: 即使睡眠被信号中断,该函数现在至少睡眠 secs ,除非信号处理程序引发异常(参见 PEP 475 作为基本原理)。

 

 

17.6. sched — Event scheduler

Source code: Lib/sched.py


The sched module defines a class which implements a general purpose event scheduler:

class sched.scheduler(timefunc=time.monotonicdelayfunc=time.sleep)

The scheduler class defines a generic interface to scheduling events. It needs two functions to actually deal with the “outside world” — timefunc should be callable without arguments, and return a number (the “time”, in any units whatsoever). If time.monotonic is not available, the timefunc default is time.time instead. The delayfuncfunction should be callable with one argument, compatible with the output of timefunc, and should delay that many time units. delayfunc will also be called with the argument 0 after each event is run to allow other threads an opportunity to run in multi-threaded applications.

Changed in version 3.3: timefunc and delayfunc parameters are optional.

Changed in version 3.3: scheduler class can be safely used in multi-threaded environments.

Example:

>>>
>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(a='default'):
...     print("From print_time", time.time(), a)
...
>>> def print_some_times():
...     print(time.time())
...     s.enter(10, 1, print_time)
...     s.enter(5, 2, print_time, argument=('positional',))
...     s.enter(5, 1, print_time, kwargs={'a': 'keyword'})
...     s.run()
...     print(time.time())
...
>>> print_some_times()
930343690.257
From print_time 930343695.274 positional
From print_time 930343695.275 keyword
From print_time 930343700.273 default
930343700.276

17.6.1. Scheduler Objects

scheduler instances have the following methods and attributes:

scheduler.enterabs(timepriorityactionargument=()kwargs={})

Schedule a new event. The time argument should be a numeric type compatible with the return value of thetimefunc function passed to the constructor. Events scheduled for the same time will be executed in the order of their priority. A lower number represents a higher priority.

Executing the event means executing action(*argument, **kwargs)argument is a sequence holding the positional arguments for actionkwargs is a dictionary holding the keyword arguments for action.

Return value is an event which may be used for later cancellation of the event (see cancel()).

Changed in version 3.3: argument parameter is optional.

New in version 3.3: kwargs parameter was added.

scheduler.enter(delaypriorityactionargument=()kwargs={})

Schedule an event for delay more time units. Other than the relative time, the other arguments, the effect and the return value are the same as those for enterabs().

Changed in version 3.3: argument parameter is optional.

New in version 3.3: kwargs parameter was added.

scheduler.cancel(event)

Remove the event from the queue. If event is not an event currently in the queue, this method will raise aValueError.

scheduler.empty()

Return true if the event queue is empty.

scheduler.run(blocking=True)

Run all scheduled events. This method will wait (using the delayfunc() function passed to the constructor) for the next event, then execute it and so on until there are no more scheduled events.

If blocking is false executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler (if any).

Either action or delayfunc can raise an exception. In either case, the scheduler will maintain a consistent state and propagate the exception. If an exception is raised by action, the event will not be attempted in future calls torun().

If a sequence of events takes longer to run than the time available before the next event, the scheduler will simply fall behind. No events will be dropped; the calling code is responsible for canceling events which are no longer pertinent.

New in version 3.3: blocking parameter was added.

scheduler.queue

Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as anamed tuple with the following fields: time, priority, action, argument, kwargs.

原文地址:https://www.cnblogs.com/rsapaper/p/7429672.html