从评估函数返回system.time

时间:2011-11-03 17:05:01

标签: r evaluation

R版本2.12,Windows XP

我试图编写一个函数(比如'g'),它接受一个参数,一个函数(比如'f'),然后返回匹配的函数。此外,包含在'g'主体内的语句是一个语句,它告诉结果对象在调用对象时返回system.time的值。一个例子将澄清。

我想要的是什么:

g <- function(f) {...}
z <- g(mean)
z(c(1, 4, 7))

带输出

user system elapsed
0.04   0.00    0.04

我有什么:

g <- function(f) {if (!exists("x")) {x <- match.fun(f)} else {system.time(x)}}
z <- g(mean)
z(c(1, 4, 7))

带输出

[1] 4

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

也许这会有所帮助:

g <- function(f){
  function(x){
    zz <- system.time(
        xx <- match.fun(f)(x)
    )
    list(value=xx, system.time=zz)
  }
}

使用中:

g(mean)(c(1, 4, 7))

$value
[1] 4

$system.time
   user  system elapsed 
      0       0       0 

您可能想要考虑如何返回值。我使用了一个列表,但另一种选择是将系统时间打印为副作用并返回计算值。

答案 1 :(得分:1)

最近我为自己做了类似的功能:

with_times <- function(f) {
    f <- match.fun(f)
    function(...) {
        .times <- system.time(res <- f(...))
        attr(res, "system.time") <- as.list(na.omit(.times))
        res
    }
}

例如:

g <- function(x,y) {r<-x+y; Sys.sleep(.5); r}
g(1, 1)
# [1] 2
g2 <- with_times(g) 
w <- g2(1, 1)

可以通过两种方式提取计时:

attributes(w)$system.time
# $user.self
# [1] 0
# $sys.self
# [1] 0
# $elapsed
# [1] 0.5

attr(w, "system.time")
# $user.self
# [1] 0
# $sys.self
# [1] 0
# $elapsed
# [1] 0.5
相关问题