2016-12-21 5 views
2

の関数として機能時間のプロファイリングのは、私は2つの入力を取る関数があるとしましょう:は、2つのパラメータ

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でこれをプロファイルする方法はありますか?

x軸とy軸にそれぞれijという実行時間の2D行列のようなものが必要です。

答えて

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... 
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 

これはあなたが言及したマトリックスを作成します。 proc.time()が3つの値を返すので、time[,1]を選択しました。関数の実行に関するものが最初のものです。R FAQ How can I time my code?

これが助けられました!

関連する問題