2012-12-01 118 views
5

我必须对大数据集(主要使用data.table,RStudio)进行大量数据操作。我想监视每个步骤的运行时间,而无需在每个步骤中显式调用system.time()。默认情况下返回system.time

在每个步骤默认情况下是否有包或简单的方式显示运行时间?

谢谢。

+1

你可以看到这个http://stackoverflow.com/questions/8439957/multi-function-tester-alternative-to-system-time – agstudy

+0

感谢agstudy 。我知道rbenchmark,但这不是我所需要的。我想有一个“副作用”,它会为每个R函数调用产生运行时间。我不确定这是否可能,尽管 – AdamNYC

+0

这很棒问题,甚至更多,因为我发现即使你在大项目的每一步中使用'system.time',并且有很多'source'调用和函数,'system.time'在源文件和内部函数中请求被忽略了(也许有一种方法可以解决这个问题,就像'print'一样,但我还没有证实,这是我的前问题的一部分研究这个确切主题的潜在问题)。 –

回答

5

这不完全是你要求的,但我写了time_file(https://gist.github.com/4183595)其中source()是一个R文件,并运行代码,然后重写该文件,插入包含每个顶级语句花费多长时间运行的注释。

time_file()变成这样:

{ 
    load_all("~/documents/plyr/plyr") 
    load_all("~/documents/plyr/dplyr") 
    library(data.table) 
    data("baseball", package = "plyr") 
    vars <- list(n = quote(length(id)), m = quote(n + 1)) 
} 

# Baseline case: use ddply 
a <- ddply(baseball, "id", summarise, n = length(id)) 

# New summary method: ~20x faster 
b <- summarise_by(baseball, group("id"), vars) 

# But still not as fast as specialised count, which is basically id + tabulate 
# so maybe able to eke out a little more with a C loop ? 
count(baseball, "id") 

到这一点:

{ 
    load_all("~/documents/plyr/plyr") 
    load_all("~/documents/plyr/dplyr") 
    library(data.table) 
    data("baseball", package = "plyr") 
    vars <- list(n = quote(length(id)), m = quote(n + 1)) 
} 

# Baseline case: use ddply 
a <- ddply(baseball, "id", summarise, n = length(id)) 
#: user system elapsed 
#: 0.451 0.003 0.453 

# New summary method: ~20x faster 
b <- summarise_by(baseball, group("id"), vars) 
#: user system elapsed 
#: 0.029 0.000 0.029 

# But still not as fast as specialised count, which is basically id + tabulate 
# so maybe able to eke out a little more with a C loop ? 
count(baseball, "id") 
#: user system elapsed 
#: 0.008 0.000 0.008 

它的顶级{块内部没有时间码,这样你就可以选择不时间的东西,你”

我不认为有没有办法自动添加计时作为顶级效果而不会以某种方式修改您运行代码的方式 - 即使用诸如time_file而不是source之类的东西。

您可能想知道每个顶级操作对代码总体速度的影响。嗯,这很容易与微基准回答;)

library(microbenchmark) 
microbenchmark(
    runif(1e4), 
    system.time(runif(1e4)), 
    system.time(runif(1e4), gc = FALSE) 
) 

所以时间增加相对小的开销(20μs的我的电脑上),但默认GC增加了每次通话约27毫秒。因此,除非您有数千个顶级通话,否则您不会看到太大的影响。

+0

我想知道是否用_every_函数调用检查时间会减慢整个爬行的速度。 –

+0

@DWin微基准加入 - 每顶层函数调用大约需要20毫秒,这对大多数脚本不太可能有明显的影响。 – hadley

+0

@Hadley does R有等价的python装饰器?我问这个,因为使用这个功能可以提高你的时间分析的清晰度。 – agstudy

0

我有充分的信贷,为这些额外的答案Freenode#R IRC频道的@jbecker,但对我的解决方案是在这里:http://adv-r.had.co.nz/Profiling.html

下面是它只是一个小的味道:

“为了理解性能,您使用了一个profiler,有许多不同类型的profiler,R使用一种相当简单的类型,称为采样或统计分析器,采样profiler每隔几毫秒就停止执行一次代码,函数正在执行(沿着用哪个函数调用该函数,等等)。例如,考虑F(),如下:”

library(lineprof) 
f <- function() { 
    pause(0.1) 
    g() 
    h() 
} 
g <- function() { 
    pause(0.1) 
    h() 
} 
h <- function() { 
    pause(0.1) 
}