ComenzarEmpieza gratis

Timings - pre-allocation

In the previous exercise, growing the vector took around 2 seconds. How long does it take when we pre-allocate the vector? The pre_allocate() function is defined below.

n <- 30000
# Fast code
pre_allocate <- function(n) {
    x <- numeric(n) # Pre-allocate
    for(i in 1:n) 
        x[i] <- rnorm(1)
    x
}

Este ejercicio forma parte del curso

Writing Efficient R Code

Ver curso

Instrucciones del ejercicio

The pre_allocate() function is available in your workspace.

  • Using system.time(), find how long it takes to run pre_allocate(n). Use the <- trick to store the result in the object res_allocate.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# Use <- with system.time() to store the result as res_allocate
n <- 30000
system.time(___ <- ___)
Editar y ejecutar código