如何在循环时加速以下操作?
count <- function(start, stepsize, threshold) {
i <- 1;
while ( start <= threshold ) {
start <- stepsize*i+start;
i <- i+1;
}
return( i-1 );
}
system.time(count(1, 0.004, 1e10))
答案 0 :(得分:10)
按上述评论计算总和:
## start + S*n*(n-1)/2 = T
## (T-start)*2/S = n*(n-1)
## n*(n-1) - (T-start)*2/S = 0
解决这个二次方程的函数:
ff <- function(start,stepsize,threshold) {
C <- (threshold-start)*2/stepsize
ceiling((-1 + sqrt(1+4*C))/2)
}
此解决方案基本上没有时间......
> system.time(cc <- count(1, 0.004, 1e10))
user system elapsed
5.372 0.056 5.642
> system.time(cc2 <- ff(1, 0.004, 1e10))
user system elapsed
0 0 0
> cc2
[1] 2236068
> cc
[1] 2236068
问题在于这是否能够解决您需要解决的确切问题。
答案 1 :(得分:0)
看起来你正试图这样做:
recount <- function(start, stepsize, threshold) {
NewCount <<- floor((threshold-start)/stepsize)
}
(fast <- system.time(recount(1, 0.004, 1e10)))
没有可测量的时间。
没有全局变量,这就是它的样子:
recount <- function(start, stepsize, threshold) {
return(floor((threshold-start)/stepsize))
}
(fast <- system.time(NewCount <- recount(1, 0.004, 1e10)))
答案 2 :(得分:0)
有一个有趣的博客如何使用一些提示加速R中的循环
Another aspect of speeding up loops in R
这是该页面中报告的示例
NROW=5000
NCOL=100
#Ex. 1 - Creation of a results matrix where its memory
#allocation must continually be redefined
t1 <- Sys.time()
x <- c()
for(i in seq(NROW)){
x <- rbind(x, runif(NCOL))
}
T1 <- Sys.time() - t1
#Ex. 2 - Creation of a results matrix where its memory
#allocation is defined only once, at the beginning of the loop.
t2 <- Sys.time()
x <- matrix(NA, nrow=NROW, ncol=NCOL)
for(i in seq(NROW)){
x[i,] <- runif(NCOL)
}
T2 <- Sys.time() - t2
#Ex. 3 - Creation of a results object as an empty list of length NROW.
#Much faster than Ex. 1 even though the size of the list is
#not known at the start of the loop.
t3 <- Sys.time()
x <- vector(mode="list", NROW)
for(i in seq(NROW)){
x[[i]] <- runif(NCOL)
}
T3 <- Sys.time() - t3
png("speeding_up_loops.png")
barplot(c(T1, T2, T3), names.arg = c("Concatenate result", "Fill empty matrix", "Fill empty list"),ylab="Time in seconds")
dev.off()
T1;T2;T3