循环在C中使RScript更高效的性能

JMF*_*MFA 0 c performance loops r

我试图计算100行x 2500列表中每行之间的成对差异数.

我有一个小的RScript,但运行时间(显然)非常高!我试图在C中编写一个循环,但我不断收到错误(compileCode).

您是否知道如何将以下循环"转换"为C?

pw.dist <- function (vec1, vec2) {

return( length(which(vec1!=vec2)) )

}

N.row <- dim(table)[1]
pw.dist.table <- array( dim = c(dim(table)[1], dim(table)[1]))

for (i in 1:N.row) {
    for (j in 1:N.row) {
        pw.dist.table[i,j] <- pw.dist(table[i,-c(1)], table[j,-c(1)])
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试这样的事情:

sig <- signature(N.row="integer", table="integer", pw.dist.table="integer")
code <- "
  for( int i = 0; i < (*N.row) - 1; i++ ) {
    for( int j = i + 1; j < *N.row; j++ ) {
      int pw.dist.table = table[j] - table[i];
    }
  }
"
f <- cfunction( sig, code, convention=".C" )
Run Code Online (Sandbox Code Playgroud)

在编程方面,我是一个完整的新手!

提前致谢.JMFA

Vin*_*ynd 5

在尝试优化代码之前,最好先检查花费的时间.

Rprof()
... # Your loops
Rprof(NULL)
summaryRprof()
Run Code Online (Sandbox Code Playgroud)

在你的情况下,循环并不慢,但你的距离函数是.

$by.total
                    total.time total.pct self.time self.pct
"pw.dist"                37.98     98.85      0.54     1.41
"which"                  37.44     97.45     34.02    88.55
"!="                      3.12      8.12      3.12     8.12
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式重写它(需要1秒钟).

# Sample data
n <- 100
k <- 2500
d <- matrix(sample(1:10, n*k, replace=TRUE), nr=n, nc=k)
# Function to compute the number of differences
f <- function(i,j) sum(d[i,]!=d[j,])
# You could use a loop, instead of outer,
# it should not make a big difference.
d2 <- outer( 1:n, 1:n, Vectorize(f) )
Run Code Online (Sandbox Code Playgroud)