定时大块? [英] Timing for chunks?

查看:74
本文介绍了定时大块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以报告计算每个块所需的时间?我正在使用一些大脚本来创建文档,所以很高兴知道时间在哪里.我确实使用了缓存功能,因此,一旦缓存了对象,使用文档就不会太慢,但是我想隔离慢块,看看除非绝对需要,否则我将如何阻止它们被重新计算. /p>

一个想法是将每个块包装在system.time()中,并在每个块输出下方或页边空白处报告system.time.

再次感谢Yihui如此出色的软件.

解决方案

您可以定义一个块挂钩函数来执行此操作.这是一个简单的示例:

```{r setup, include=FALSE}
knitr::knit_hooks$set(timeit = local({
  now = NULL
  function(before, options) {
    if (before) {
      now <<- Sys.time()
    } else {
      res = difftime(Sys.time(), now)
      now <<- NULL
      # use options$label if you want the chunk label as well
      paste('Time for this code chunk:', as.character(res))
    }
  }})
)
```

Test it:

```{r test-a, timeit = TRUE}
Sys.sleep(2)
```

根据您使用的文档格式,您可能需要格式化该挂钩返回的字符串.从数据块挂钩返回的字符结果将与原始输出合并,而其他类型的输出将被忽略.

Is there any way to report how much time it takes to compute each chunk? I am working on creating a document from some large scripts, and it would be nice to know where the time is taken. I do use the caching feature, so of course once objects are cached, it is not too slow to work with the document, but I'd like to isolate the slow chunks to see how I can stop them being recomputed unless absolutely needed.

One thought was e.g. to wrap each chunk in system.time() and report the system.time underneath each chunk output, or in the margin...

Thanks again Yihui for such excellent software.

解决方案

You can define a chunk hook function to do this. Here is a quick example:

```{r setup, include=FALSE}
knitr::knit_hooks$set(timeit = local({
  now = NULL
  function(before, options) {
    if (before) {
      now <<- Sys.time()
    } else {
      res = difftime(Sys.time(), now)
      now <<- NULL
      # use options$label if you want the chunk label as well
      paste('Time for this code chunk:', as.character(res))
    }
  }})
)
```

Test it:

```{r test-a, timeit = TRUE}
Sys.sleep(2)
```

Depending on the document format that you work with, you may want to format the character string returned by the hook. Character results returned from the chunk hooks are combined with the original output, and other types of output are ignored.

这篇关于定时大块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆