Почему тиблы медленнее, чем матрицы в цикле for, но быстрее, когда доступ осуществляется очень часто? - PullRequest
1 голос
/ 06 мая 2019

В агентском проекте моделирования я подумывал использовать tidyverse a tibble вместо matrix.Я проверил эффективность обоих с очень простой ПРО (см. Ниже), где я моделирую население, где люди стареют, умирают и рождаются.Типично для ПРО, я использую цикл for и индексацию.

При сравнительном анализе двух структур данных (см. График здесь: https://github.com/marcosmolla/tibble_vs_matrix) матрица намного быстрее, чем тиббл. Однако для прогонов 10e6 этот результат фактически инвертируется. И я понятия не имею,почему.

Было бы здорово понять этот результат, чтобы сообщить, буду ли я использовать тиблы или матрицы в будущем для этого вида использования.

Спасибо всем за любой вклад!

fig1

# This code benchmarks the speed of tibbles versus matrices. This should be useful for evaluating the suitability of tibbles in a ABM context where matrix data is frequently altered in matrices (or vectors).

library(tidyverse)
library(reshape2)
library(cowplot)

lapply(c(10^1, 10^2, 10^3, 10^4, 10^5, 10^6), function(runtime){
  # Set up tibble
  indTBL <- tibble(id=1:100,
         type=sample(1:3, size=100, replace=T),
         age=1)

  # Set up matrix (from tibble)
  indMAT <- as.matrix(indTBL)

  # Simulation run with tibble
  t <- Sys.time()
  for(i in 1:runtime){
    # increase age
    indTBL$age <- indTBL[["age"]]+1

    # replace individuals by chance or when max age
    dead <- (1:100)[runif(n=100,min=0,max=1)<=0.01 | indTBL[["age"]]>100]
    indTBL[dead, "age"] <- 1
    indTBL[dead, "type"] <- sample(1:3, size=length(dead), replace=T)
  }
  tibbleTime <- as.numeric(Sys.time()-t)

  # Simulation run with matrix
  t <- Sys.time()
  for(i in 1:runtime){
    # increase age
    indMAT[,"age"] <- indMAT[,"age"]+1

    # replace individuals by chance or when max age
    dead <- (1:100)[runif(n=100,min=0,max=1)<=0.01 | indMAT[,"age"]>100]
    indMAT[dead, "age"] <- 1
    indMAT[dead, "type"] <- sample(1:3, size=length(dead), replace=T)
  }
  matrixTime <- as.numeric(Sys.time()-t)

  # Return both run times
  return(data.frame(tibbleTime=tibbleTime, matrixTime=matrixTime))
}) %>% bind_rows() -> res

# Prepare data for ggplot
res$power <- 1:nrow(res)
res_m <- melt(data=res, id.vars="power")

# Line plot for results
ggplot(data=res_m, aes(x=power, y=value, color=variable)) + geom_point() + geom_line() + scale_color_brewer(palette="Paired") + ylab("Runtime in sec") + xlab(bquote("Simulation runs"~10^x))

1 Ответ

0 голосов
/ 06 мая 2019

Спасибо вам обоим за ваши ответы. Я использовал пакет microbenchmark для правильной оценки. Теперь я обнаружил, что для 10e6 работает матрица еще быстрее.

  indTBL <- tibble(id=1:100,
                   type=sample(1:3, size=100, replace=T),
                   age=1)

  # Set up matrix (from tibble)
  indMAT <- as.matrix(indTBL)

  # Simulation run with tibble
  runtime <- 10^6
  microbenchmark(
  tib=for(i in 1:runtime){
    # increase age
    indTBL$age <- indTBL[["age"]]+1

    # replace individuals by chance or when max age
    dead <- (1:100)[runif(n=100,min=0,max=1)<=0.01 | indTBL[["age"]]>100]
    indTBL[dead, "age"] <- 1
    indTBL[dead, "type"] <- sample(1:3, size=length(dead), replace=T)
  },

  # Simulation run with matrix
  mat=for(i in 1:runtime){
    # increase age
    indMAT[,"age"] <- indMAT[,"age"]+1

    # replace individuals by chance or when max age
    dead <- (1:100)[runif(n=100,min=0,max=1)<=0.01 | indMAT[,"age"]>100]
    indMAT[dead, "age"] <- 1
    indMAT[dead, "type"] <- sample(1:3, size=length(dead), replace=T)
  }, times=1
  )

Результат

Unit: seconds
 expr      min       lq     mean   median       uq      max neval cld
  tib 80.22042 81.45051 82.26645 82.68061 83.28946 83.89831     3   b
  mat 20.44746 20.66974 20.75168 20.89202 20.90378 20.91555     3  a 

Спасибо, Ilrs и MrFlick за этот совет.

...