我怎樣才能加速以下循環?R加速while循環
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))
我怎樣才能加速以下循環?R加速while循環
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))
工作出款項在上面的評論:
## 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
該曲關鍵是這是否能夠推廣到您需要解決的確切問題。
它看起來像你試圖做到這一點:
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)))
??但是這並沒有給出與OP的測試代碼相同的答案......並且設置一個全局變量而不是返回一個值是相當單一的... – 2012-01-12 16:13:44
有一個有趣的博客如何加快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
對於這個特定的問題,我會制定出手工加總 - 例如你知道從1到n的和(i)是n *(n + 1) - 然後求解適當的二次方程並進行調整。你也可以字節編譯......是更大問題的一部分,還是隻需要解決這個確切的問題? – 2012-01-08 15:17:19
就是這樣!非常感謝! – rua 2012-01-08 16:27:28