分析功能时间作为两个参数的函数

时间:2016-12-21 02:49:28

标签: r profiling

我们说我有一个带两个输入的函数:

myfun = function(i,j){
  fac = factorial(i)
  c0 = crossprod(matrix(rnorm(j*j),nrow=j), matrix(rnorm(j*j),nrow=j))
  return(fac + c0)
}

我想了解执行时间如何随ij而变化。

有没有办法在R中对此进行分析?

我想要一些东西来获得类似于执行时间的2D矩阵,分别在x和y轴上有ij

2 个答案:

答案 0 :(得分:0)

鉴于您所描述的功能,您应该能够分别对每个参数进行分析,然后根据您的选择添加时间,因为参数彼此独立。但是,为了回答你的问题,我想出了这个问题:

# wrap function in timer
myfun_time <- function(i,j, type = "user.self"){

  system.time(myfun(i,j))[type]

} 

# choose points to evaluate at
i_vals <- c(0,10,50,100,120)
j_vals <- c(0,10,50,100,150)

# create evaluation matrix (all combinations of points)
eval_mat <- expand.grid(i = i_vals, j = j_vals)

# create matrix to help with location of points when moving from vector to matrix
loc_mat <- as.matrix(expand.grid(i = 1:length(i_vals), j = 1:length(j_vals)))

# run test
results_vec <- mapply(myfun_time, i = eval_mat$i, j = eval_mat$j)

# empty matrix to store results
results_mat <- matrix(NA, nrow = sqrt(nrow(eval_mat)), ncol = sqrt(nrow(eval_mat)), 
              dimnames = list(i_vals,j_vals))

# move results vector to matrix
results_mat[loc_mat] <- results_vec

# you can also repeat this and average the results...

答案 1 :(得分:0)

您可以使用proc.time命令。这应该有效:

# Creates a matrix with i_max, j_max dimentions
times <- matrix(nrow = i_max, ncol = j_max)

for (i in 1:i_max) {
    for (j in 1:j_max) {
        # Start the clock
        ptm <- proc.time()

        # Execution
        exec <- myfun(i, j)

        # Final time
        time <- proc.time() - ptm

        # Adding it to the time matrix
        times[i, i] <- time[,1]
    }
}

# Show the times matrix
times

这将创建您提到的矩阵。我之所以选择time[,1],是因为proc.time()返回3个值,而关于函数执行的值是第一个,您可以在此处阅读:R FAQ How can I time my code?

希望这有帮助!