R microbenchmark:如何将相同的参数传递给评估函数?

Dan*_*iel 5 r microbenchmark r-raster

我想评估使用不同文件类型(geotiff、二进制)或对象(RasterBrick、RasterStack)从栅格时间序列中提取数据的时间。我创建了一个函数,该函数将从栅格​​对象的随机点提取时间序列,然后使用微基准测试它。

前任。:

# read a random point from a raster stack
sample_raster <- function(stack) {
  poi <- sample(ncell(stack), 1)
  raster::extract(stack, poi)
}

# opening the data using different methods
data_stack <- stack(list.files(pattern = '3B.*tif'))
data_brick <- brick('gpm_multiband.tif')

bench <- microbenchmark(
  sample_stack = sample_raster(data_stack),
  sample_brick = sample_raster(data_brick),
  times = 10
)

boxplot(bench)

# this fails because sampled point is different
bench <- microbenchmark(
  sample_stack = sample_raster(data_stack),
  sample_brick = sample_raster(data_brick),
  times = 10,
  check = 'equal'
)
Run Code Online (Sandbox Code Playgroud)

我在此处包含了我的数据集的示例

由此,我可以看到RasterBrick上的采样比堆栈更快(R Raster 手册也这么说——很好)。问题是我在每个评估表达式的不同点进行采样。所以我无法检查结果是否相同。我想做的是在两个对象的同一位置(poi)进行采样。但每次迭代的位置都不同。我尝试在微基准测试中使用设置选项,但据我了解,设置是在每个函数计时之前评估的,而不是每次迭代一次。因此使用该设置生成随机POI将不起作用。

是否可以将相同的参数传递给在微基准测试中评估的函数?

结果

解决方案使用microbenchmark

按照建议(并在下面解释),我bench通过press通话尝试了该软件包。但由于某种原因,它比在每次迭代时设置相同的种子要慢microbenchmark,如mnist建议的那样。所以我最终回到了microbenchmark。这是我正在使用的代码:

library(microbenchmark)
library(raster)

annual_brick <- raster::brick('data/gpm_tif_annual/gpm_2016.tif')
annual_stack <- raster::stack('data/gpm_tif_annual/gpm_2016.tif')

x <- 0
y <- 0

bm <- microbenchmark(
  ext = {
    x <- x + 1
    set.seed(x)
    poi = sample(raster_size, 1)
    raster::extract(annual_brick, poi)
  },
  slc = {
    y <- y + 1
    set.seed(y)
    poi = sample(raster_size, 1)
    raster::extract(annual_stack, poi)
  },
  check = 'equal'
)
Run Code Online (Sandbox Code Playgroud)

解决方案使用bench::press

为了完整起见,这就是我所做的,使用bench::press. 在此过程中,我还将用于选择随机单元的代码与点采样函数分开。所以我只能对代码的点采样部分进行计时。我是这样做的:

library(bench)
library(raster)

annual_brick <- raster::brick('data/gpm_tif_annual/gpm_2016.tif')
annual_stack <- raster::stack('data/gpm_tif_annual/gpm_2016.tif')

bm <- bench::press(
  pois = sample(ncell(annual_brick), 10),
  mark(
    iterations = 1,
    sample_brick = raster::extract(annual_brick, pois),
    sample_stack = raster::extract(annual_stack, pois)
  )
)
Run Code Online (Sandbox Code Playgroud)

mni*_*ist 4

我的方法是为 microbenchmark 中的每个选项设置相同的席位,但在每次函数调用之前更改它们。查看输出以及最终如何将相同的席位用于两个呼叫

x <- 0
y <- 0

microbenchmark::microbenchmark(
  "checasdk" = {
    # increase seat value by 1
    x <- x + 1
    print(paste("1", x))
    set.seed(x)}, 

  "check2" = {
    y <- y + 1
    print(paste("2", y))
    set.seed(y)
    }
  )
Run Code Online (Sandbox Code Playgroud)