R中的system.time(exp)输出中,“user”和“system”时间分别代表什么意思?

115

我正在使用system.time(expression)来测量R函数的执行时间。

对于这个调用,我得到的输出是

system.time(myfunction())

是:

    user  system elapsed   
  117.36    5.65  127.86

What does 'user' and 'system' measure?


1
http://en.wikipedia.org/wiki/Time_(Unix)#User_Time_vs_System_Time - manojlds
1
这个问题可以使用更好的标题,比如“什么是'user'和'system'时间测量?”这将使浏览列表的人更清楚地了解问题。 - Sharpie
5个回答

55
我曾阅读过有关 usersystem 运行时间差异的最清晰解释,这是由 William Dunlap 在 [R-help] 上提供的:

"用户 CPU 时间" 是指当前进程(即当前 R 会话)使用的 CPU 时间,“系统 CPU 时间” 是指操作系统内核(kernel)代表当前进程使用的 CPU 时间。操作系统用于打开文件、输入或输出、启动其他进程以及查看系统时钟等操作:这些操作涉及许多进程必须共享的资源。

尽管 ?proc.time 返回了类似的信息,但对我来说,这个描述更容易理解。

52

这个问题在?proc.time中有所讨论(system.time()返回一个类为"proc.time"的对象):

Details:

     ‘proc.time’ returns five elements for backwards compatibility, but
     its ‘print’ method prints a named vector of length 3.  The first
     two entries are the total user and system CPU times of the current
     R process and any child processes on which it has waited, and the
     third entry is the ‘real’ elapsed time since the process was
     started.

...并且

Value:

....

     The definition of ‘user’ and ‘system’ times is from your OS.
     Typically it is something like

     _The ‘user time’ is the CPU time charged for the execution of user
     instructions of the calling process. The ‘system time’ is the CPU
     time charged for execution by the system on behalf of the calling
     process._

32

这里有些简单的解释:

已过时间 是表达式被CPU(s)计算的时间。

用户时间 是指墙上的时钟时间,即作为用户所经历的时间。

通常这两个时间相对接近。但在其他情况下可能会有所不同。例如:

  • 如果已过时间 > 用户时间,则意味着CPU正在等待其他操作(可能是外部操作)完成。
  • 如果已过时间 < 用户时间,则意味着您的机器有多个核心并且能够使用它们。

9
我认为你可能把“经过时间”和“用户时间”搞反了(在你的定义中;你给出的例子对我来说是有意义的)。例如,在运行使用并行处理的代码时,“用户时间”可以比“经过时间”长得多,因为在墙钟时间的单个滴答声中,一群CPU可以消耗大量的“用户”时间。 - Daniel Kessler
一项实验向我展示了实时时间是经过的时间,因此 @DanielKessler 在这里似乎是正确的。 - Julien

18

以下来自维基百科,由于这些都是通用术语,因此:

“用户CPU时间”一词可能一开始有点误导人。要明确的是,总时间(真实CPU时间)是CPU花费在为程序执行某些操作和代表程序为内核执行系统调用所花费的时间的组合。当程序循环遍历数组时,它正在累积用户CPU时间。相反,当程序执行像exec或fork这样的系统调用时,它正在累积系统CPU时间。

http://en.wikipedia.org/wiki/Time_(Unix)#User_Time_vs_System_Time


2
由于这些时间变量是由您的操作系统定义的,因此您可以通过在Unix shell中执行man time来检索有关它们如何计算的信息:
“……这些统计数据包括(i)调用和终止之间经过的实际流逝时间,(ii)用户CPU时间(由times(2)返回的struct tms中的和值的总和),以及(iii)系统CPU时间(由times(2)返回的struct tms中的和值的总和)。”
提到的时间变量的定义可以在这里找到: 用户CPU时间。 系统CPU时间。 终止的子进程的用户CPU时间。 终止的子进程的系统CPU时间。
在daroczig的回答和SO上的其他地方中,对用户时间和系统时间之间的差异进行了澄清:

tms_utime元素是执行您的代码或C库中的代码所花费的时间。 tms_stime元素是在内核中代表您执行代码所花费的时间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接