如何使功能执行得更快? [英] How to make function perform faster?
问题描述
我具有以下功能: http://i.stack.imgur.com/yXA67.png ,其中 mu 是矩阵(n_X行和n_Y列). d_X和d_Y是距离矩阵.
I have following function: http://i.stack.imgur.com/yXA67.png, where mu is matrix (n_X rows and n_Y columns). d_X and d_Y are distance matrices.
在R中实现此功能的一种方法是:
One way to implement this function in R would be:
H_mu <- function(mu, d_X, d_Y){
value <- 0
for(i in 1:nrow(d_X)){
for(ii in 1:nrow(d_X)){
for(j in 1:nrow(d_Y)){
for(jj in 1:nrow(d_Y)){
value <- value + mu[i,j]*mu[ii,jj]*abs(d_X[i,ii]-d_Y[j,jj])
}}}}
}
例如:
X <- matrix(rep(1,50),nrow = 50)
Y <- matrix(c(1:50),nrow = 50)
d_X <- as.matrix(dist(X, method = "euclidean", diag = T, upper = T))
d_Y <- as.matrix(dist(Y, method = "euclidean", diag = T, upper = T))
mu <- matrix(1/50, nrow = nrow(X), ncol = nrow(Y))
H_mu(mu, d_X, d_Y)
[1] 41650
> system.time(H_mu(mu, d_X, d_Y))
user system elapsed
22.67 0.01 23.06
仅用50点计算就需要23秒.
Only with 50 points calculations take 23 seconds.
如何加快此功能?
推荐答案
似乎@Marat Talipov的建议是可行的.如果您不习惯使用C ++进行编码,则可以使用 typedFunction 自动生成用于简单的R函数.假定存在显式的return
调用,它将使用R函数及其参数及其类型,并返回文本代码.
Seems like @Marat Talipov's suggestion is way to go. If you are not comfortable with coding in C++, you can use typedFunction to auto-generate Rcpp code for simple R functions. It takes R function and it's arguments along with their types, assuming that there is explicit return
call, and returns text code.
H_mu <- function(mu, d_X, d_Y){
value <- 0
for(i in 1:nrow(d_X)){
for(ii in 1:nrow(d_X)){
for(j in 1:nrow(d_Y)){
for(jj in 1:nrow(d_Y)){
value <- value + mu[i,j]*mu[ii,jj]*abs(d_X[i,ii]-d_Y[j,jj])
}}}}
return (value)
}
在这里,我已将return(value)
添加到您的H_mu
函数
Here I've added return(value)
to your H_mu
function
text <- typedFunction(H_mu, H_mu='double', value='double',
mu='NumericVector',
d_X='NumericVector',
d_Y='NumericVector',
i='int',
ii='int',
jj='int',
j='int')
cat(text)
将结果复制并粘贴到Rcpp编辑器中,稍作调整后,您就可以执行H_mu_typed
函数.
Copy-paste the outcome to your Rcpp editor, and after little tweaking you have executable H_mu_typed
function.
Rcpp::cppFunction('double H_mu_typed(NumericMatrix mu, NumericMatrix d_X, NumericMatrix d_Y) {
double value=0;
value = 0;
for (int i = 0; i <d_X.nrow(); i++) {
for (int ii = 0; ii < d_X.nrow(); ii++) {
for (int j = 0; j < d_Y.nrow(); j++) {
for (int jj = 0; jj < d_Y.nrow(); jj++) {
value = value + mu(i, j) * mu(ii, jj) * abs(d_X(i, ii) - d_Y(j, jj));
};
};
};
};
return(value);
}
')
享受C ++的速度.
H_mu_typed(mu, d_X, d_Y)
[1] 41650
system.time(H_mu_typed(mu, d_X, d_Y))[3]
elapsed
0.01
这篇关于如何使功能执行得更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!