Yih*_*Xie 12
您可以定义一个块挂钩函数来执行此操作.这是一个简单的例子:
```{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)
```
Run Code Online (Sandbox Code Playgroud)
根据您使用的文档格式,您可能希望格式化钩子返回的字符串.从块钩子返回的字符结果与原始输出组合,并忽略其他类型的输出.