R 教材:迴圈 |
# File name: loop_for_1.r my.loop <- 20 m.dim <- list(nrow = 200000, ncol = 10) m <- matrix(1, nrow = m.dim$nrow, ncol = m.dim$ncol) ret <- 0 start <- Sys.time() for(k in 1 : my.loop){ for (i in 1 : m.dim$nrow){ for (j in 1 : m.dim$ncol){ ret <- ret + m[i, j] } } } Sys.time() - start |
# File name: loop_for_2.r my.loop <- 20 m.dim <- list(nrow = 200000, ncol = 10) m <- matrix(1, nrow = m.dim$nrow, ncol = m.dim$ncol) ret <- 0 start <- Sys.time() for(k in 1 : my.loop){ for (j in 1 : m.dim$ncol){ for (i in 1 : m.dim$nrow){ ret <- ret + m[i, j] } } } Sys.time() - start |
# File name: loop_apply.r my.loop <- 20 m.dim <- list(nrow = 200000, ncol = 10) m <- matrix(1, nrow = m.dim$nrow, ncol = m.dim$ncol) ret <- 0 start <- Sys.time() for(k in 1 : my.loop){ ret <- ret + sum(apply(m, 1, sum)) } Sys.time() - start |
# File name: loop_rowSums.r my.loop <- 20 m.dim <- list(nrow = 200000, ncol = 10) m <- matrix(1, nrow = m.dim$nrow, ncol = m.dim$ncol) ret <- 0 start <- Sys.time() for(k in 1 : my.loop){ ret <- ret + sum(rowSums(m)) } Sys.time() - start |
c File name: lood_dyn.f c For dynamical load compile by g77. c SHELL> g77 -c loop_dyn.f ; g77 -shared -o loop_dyn.so loop_dyn.o subroutine dynsum(nrow, ncol, m, ret) integer i, j, nrow, ncol real*8 m(nrow, ncol), ret ret = 0 do j = 1, ncol do i = 1, nrow ret = ret + m(i, j) end do end do return end c Output is a shared library "loop_dyn.so" can called by R. |
# File name: loop_dyn.r dyn.load("loop_dyn.so") # For Windows will like this # dyn.load("C:/Windows/Desktop/loop_dyn.dll") my.loop <- 20 m.dim <- list(nrow = 200000, ncol = 10) m <- matrix(1, nrow = m.dim$nrow, ncol = m.dim$ncol) ret <- 0 dynsum.f <- function(m) { ret <- .Fortran("dynsum", nrow = nrow(m), ncol = ncol(m), m = as.double(m), ret = as.double(m)) ret$ret } start <- Sys.time() for(k in 1 : my.loop){ ret <- ret + dynsum.f(m) } Sys.time() - start dyn.unload("loop_dyn.so") # For Windows will like this # dyn.unload("C:/Windows/Desktop/loop_dyn.dll") |
Sum by Loop | for 1 | for 2 | apply | rowSums | dyn | |
---|---|---|---|---|---|---|
Time (secs) | 331 | 307 | 117 | 2 | 19 |
陳韋辰 (04/08/19) --- |