理解 time.perf_counter()和 time.process_time()

我有一些关于新函数 time.perf_counter()time.process_time()的问题。

对于前者,从文档中可以看出:

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

所有系统的“最高分辨率”是否相同?或者它总是稍微取决于,例如,我们是否使用 linux 或者 windows?
这个问题来自于阅读 time.time()的文档时发现“并不是所有的系统都能提供比1秒更好的时间精度”,那么他们现在怎样才能提供更好更高的分辨率呢?

关于后者,time.process_time():

返回当前进程的系统和用户 CPU 时间之和的值(小数秒)。不包括睡眠时间。根据定义,它是流程范围的。返回值的引用点是未定义的,因此只有连续调用的结果之间的差异是有效的。

我不明白,什么是“系统时间”和“用户 CPU 时间”? 有什么区别?

85265 次浏览

There are two distincts types of 'time', in this context: absolute time and relative time.

Absolute time is the 'real-world time', which is returned by time.time() and which we are all used to deal with. It is usually measured from a fixed point in time in the past (e.g. the UNIX epoch of 00:00:00 UTC on 01/01/1970) at a resolution of at least 1 second. Modern systems usually provide milli- or micro-second resolution. It is maintained by the dedicated hardware on most computers, the RTC (real-time clock) circuit is normally battery powered so the system keeps track of real time between power ups. This 'real-world time' is also subject to modifications based on your location (time-zones) and season (daylight savings) or expressed as an offset from UTC (also known as GMT or Zulu time).

Secondly, there is relative time, which is returned by time.perf_counter and time.process_time. This type of time has no defined relationship to real-world time, in the sense that the relationship is system and implementation specific. It can be used only to measure time intervals, i.e. a unit-less value which is proportional to the time elapsed between two instants. This is mainly used to evaluate relative performance (e.g. whether this version of code runs faster than that version of code).

On modern systems, it is measured using a CPU counter which is monotonically increased at a frequency related to CPU's hardware clock. The counter resolution is highly dependent on the system's hardware, the value cannot be reliably related to real-world time or even compared between systems in most cases. Furthermore, the counter value is reset every time the CPU is powered up or reset.

time.perf_counter returns the absolute value of the counter. time.process_time is a value which is derived from the CPU counter but updated only when a given process is running on the CPU and can be broken down into 'user time', which is the time when the process itself is running on the CPU, and 'system time', which is the time when the operating system kernel is running on the CPU on behalf on the process.