Created
June 17, 2020 03:02
-
-
Save ryanbthomas/cdc165230829787a6cd0efe717dcb3b0 to your computer and use it in GitHub Desktop.
Vectorize Example
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) | |
library(purrr) | |
library(tibble) | |
num_sims <- 1000 | |
lambda <- 0.15 | |
mu <- 7 | |
sigma <- 2 | |
non_vectorized_simulation <- function(num_sims) { | |
losses <- vector(mode = "list", length = num_sims) | |
num_claims <- rpois(num_sims, lambda = lambda) | |
for (i in seq_len(num_sims)) { | |
losses[[i]] <- rlnorm(num_claims[i], meanlog = mu, sdlog = sigma) | |
} | |
purrr::map_dfr(losses, ~ tibble::tibble(loss = .x), .id = "simyear") | |
} | |
vectorized_simulation <- function(num_sims) { | |
num_claims <- rpois(num_sims, lambda = lambda) | |
losses <- rlnorm(sum(num_claims), meanlog = mu, sdlog = sigma) | |
simyear <- seq_len(num_sims) | |
has_losses <- num_claims > 0 | |
years_with_losses <- simyear[has_losses] | |
num_losses <- num_claims[has_losses] | |
year_idx <- seq_along(num_losses) | |
purrr::map2_dfr(year_idx, num_losses, | |
~ tibble::tibble(simyear = years_with_losses[.x], | |
loss = losses[.x + (seq_len(.y) - 1)])) | |
} | |
results <- microbenchmark::microbenchmark( | |
nonvec = non_vectorized_simulation(50000), | |
vec = vectorized_simulation(50000), | |
times = 10 | |
) | |
print(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment