gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:54 24 4
gpt4 key购买 nike

我正在尝试计算 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)])
}
}

我正在尝试类似的东西:

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" )

在编程方面我完全是个新手!

提前致谢。金发协会

最佳答案

在尝试优化代码之前,检查时间花在了哪里总是一个好主意。

Rprof()
... # Your loops
Rprof(NULL)
summaryRprof()

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

$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

你可以重写如下(耗时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) )

关于c - 在 C 中循环使 RScript 性能更高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com