Created
April 25, 2018 21:30
-
-
Save alexperrone/78588674d2e00b98ed682dccb2854288 to your computer and use it in GitHub Desktop.
Benchmark vectorization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(microbenchmark) | |
options(digits = 3) | |
# Initialize variables. | |
vec <- 1:1e7 # initialize input vector, change size here | |
range <- seq_along(vec) # for bare for-loop | |
sum_unallocated <- function(x){ | |
result <- c() | |
for (i in seq_along(x)){ | |
result[i] <- x[i] + 1 | |
} | |
return(result) | |
} | |
sum_allocated <- function(x){ | |
result <- vector(mode = "numeric", length=length(x)) | |
for (i in seq_along(x)){ | |
result[i] <- x[i] + 1 | |
} | |
return(result) | |
} | |
sum_apply <- function(x){ | |
result <- sapply(x, FUN = function(y) { y + 1 }) | |
return(result) | |
} | |
sum_vectorized <- function(x){ | |
result <- x + 1 | |
return(result) | |
} | |
empty_for_loop <- function(x){ | |
for (i in seq_along(x)){ } | |
} | |
bare_for_loop <- function(range){ | |
for (i in range){ } | |
} | |
# Benchmark all results. | |
microbenchmark(a <- sum_unallocated(vec), | |
b <- sum_allocated(vec), | |
c <- sum_apply(vec), | |
d <- sum_vectorized(vec), | |
empty_for_loop(vec), | |
absolutely_bare_for_loop(range), | |
times = 10L, unit = "s") | |
# Unit: seconds | |
# expr min lq mean median uq max neval cld | |
# a <- sum_unallocated(vec) 4.2620 4.3079 4.6143 4.5841 4.7909 5.317 10 c | |
# b <- sum_allocated(vec) 0.6237 0.6508 0.7549 0.7036 0.7237 1.305 10 b | |
# c <- sum_apply(vec) 9.3891 10.4658 11.1595 10.9814 12.0064 12.718 10 d | |
# d <- sum_vectorized(vec) 0.0261 0.0298 0.0974 0.0903 0.1554 0.214 10 a | |
# empty_for_loop(vec) 0.0938 0.0952 0.0987 0.0995 0.1011 0.104 10 a | |
# bare_for_loop(range) 0.0878 0.0883 0.0991 0.0918 0.0953 0.164 10 a | |
# Check that all results are equal. | |
all.equal(a, b) | |
all.equal(b, c) | |
all.equal(c, d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment