R:通过 XTS 对象与 Matrix 进行子选择:为什么这样的性能受到影响?

R: Sub-selecting through XTS object vs Matrix: Why such a performance hit?

在相同大小的 XTS 对象和 R 矩阵上的 for 循环中进行子选择会产生截然不同的性能。在我机器上的以下示例中,矩阵代码需要 0.42 秒,而 XTS 代码需要 31.64 秒。假设我必须做这样的循环,我应该使用 as.matrix 预先转换我所有的 XTS 对象,还是有办法从 xts 对象获得更高的性能?

library(xts)

NumRows <- 1000000
NumCols <- 30
theMatrix <- matrix(rep(1,NumRows*NumCols),nrow=NumRows)
theXTS <- xts(theMatrix,Sys.Date()+1:NumRows)

system.time({  

  for(k in 1:NumRows){
    DataPoint <- theMatrix[k,1]
  }

})

system.time({  

  for(k in 1:NumRows){
    DataPoint <- theXTS[k,1]
  }

})

是的。简短的回答是,当您对 xts 对象进行子集化时,您是从向量中提取相关时间,并且还从矩阵中提取相关行,这在计算时间上比仅从矩阵中提取组件更昂贵。您通常希望将数据保存为 xts 格式,以便通过时间轻松地对数据进行子集化,但您可以先调用 coredata(比 as.matrix 更快),这会公开数据矩阵,在通过整数索引

xts 对象进行子集化之前

阅读?coredata

> class(coredata(theXTS))
[1] "matrix"

# Compare benchmark below against subsetting with an existing matrix
theXTS_matrix <- as.matrix(theXTS)

library(microbenchmark)
microbenchmark(theXTS_matrix[5, 7:10], coredata(theXTS), 

coredata(theXTS)[5, 7:10],
                   theXTS[5, 7:10], as.matrix(theXTS)[5, 7:10])
# Unit: nanoseconds
# expr    min       lq      mean   median       uq    max neval
# theXTS_matrix[5, 7:10]    663   1087.5   1479.39   1254.0   1569.0   9062   100
# coredata(theXTS)  10456  12090.5  13413.92  13122.0  14269.0  24106   100
# coredata(theXTS)[5, 7:10]  11703  12959.5  15193.21  14298.5  15499.5  56137   100
# theXTS[5, 7:10]  27519  30293.5  32669.63  31805.5  33130.5  57130   100
# as.matrix(theXTS)[5, 7:10] 200927 205187.5 209949.47 206926.0 212582.0 330426   100

coredata 开销很小,但子集化速度更快。

提供了几个要点,但它们没有解释这两个函数之间差异的大小。我还注意到问题中没有 "searching" 完成:ij 已经是整数,所以它只是一个直接索引操作。

大部分速度差异可归因于在 [.xts 中完成的所有检查。即使没有那些,你应该期望 [.xts 在矩阵上比 [ 稍微慢一些,因为 xts 对象总是需要做一个额外的操作:子集索引。

R> system.time(for(k in 1:10000) theMatrix[k, 1:10])
   user  system elapsed 
  0.012   0.000   0.015 
R> system.time(for(k in 1:10000)
+   .Call('_do_subset_xts', theXTS, k, 1:10, F, PACKAGE='xts'))
   user  system elapsed 
  0.016   0.000   0.018