解读 R 中 system.time 函数的输出

Jesse John 2023年1月30日
  1. 理解 R 中 system.time 函数输出中的术语
  2. R 中的 system.time 输出示例
解读 R 中 system.time 函数的输出

system.time() 函数是我们可以用来估计代码执行所需时间的工具之一。它的输出给出了三个值:用户、系统和经过的时间(以秒为单位)。

在对所涉及的术语进行简要说明后,我们将查看此函数的输出示例,以了解每个值所测量的内容。

理解 R 中 system.time 函数输出中的术语

system.time() 函数的输出中,最容易理解的术语是第三个值:elapsed。它测量代码块运行时经过的时钟时间。

在几乎所有情况下,这对用户都很重要:他们必须等待 R 完成运行代码。

另外两个,用户和系统的组合,测量 CPU 执行代码块的时间。

简单来说,我们可以将它们视为如下。

用户时间是处理用户应用程序代码(R 代码)所花费的 CPU 时间。如果用户应用程序访问系统资源,则该处理时间将报告为系统时间。

参考资料部分中给出的 Wikipedia 文章提供了有关 CPU 时间的这两个组成部分的简要技术细节。

R 中的 system.time 输出示例

下面的简单示例显示了如何使用 system.time() 函数。

示例代码:

system.time({
    print("Hello to R.")
})

输出:

[1] "Hello to R."
   user  system elapsed
  0.001   0.000   0.001

system.time() 函数在代码块之前和之后调用 proc.time() 函数,并给出了区别。

它等同于以下内容。

示例代码:

x = proc.time()
print("Hello to R.")
y = proc.time()
y-x

输出:

> x = proc.time()
> print("Hello to R.")
[1] "Hello to R."
> y = proc.time()
> y-x
   user  system elapsed
  0.001   0.001   0.001

看下面两个例子来了解用户时间和系统时间的区别。

在第一个示例中,R 计算了 1000 次并且只打印了一次。多次运行此代码块并检查结果。

示例代码:

system.time({
    x=0
    for(i in 1:1000){
        x = x+1
    }
    print(x)
})

输出:

   user  system elapsed
  0.009   0.000   0.011

虽然用户时间是正数,但系统时间在大多数情况下几乎为 0。

现在,让我们看另一个执行相同计算但打印 1000 次的代码示例。

示例代码:

system.time({
    x=1
    for(i in 1:1000){
        x = x+1
        print(x)
    }
})

输出:

   user  system elapsed
  0.093   0.026   0.120

现在,我们发现系统时间也是正数。这是因为 1000 个 print 语句使 R 可以访问操作系统的输入输出资源。

最后,为了说明经过的时间,让我们看一个 CPU 长时间空闲的例子。

示例代码:

system.time({
    Sys.sleep(5) # Time in seconds.
})

输出:

   user  system elapsed
  0.013   0.006   5.000

我们发现经过的时间远远超过 CPU 时间。它(几乎)与我们指定的睡眠时间相同,因为代码没有做任何其他事情。

参考

以下两篇 Wikipedia 文章提供了与 CPU 时间相关的简要技术细节。

  1. CPU 时间
  2. 用户空间和内核空间
作者: Jesse John
Jesse John avatar Jesse John avatar

Jesse is passionate about data analysis and visualization. He uses the R statistical programming language for all aspects of his work.