【发布时间】:2013-06-11 11:53:21
【问题描述】:
与question 类似,我运行了一个微基准测试来从大型矩阵中读取单个元素。我很惊讶地看到使用行名时性能会下降多少:
m = matrix(1, nrow=1000000, ncol=10)
rownames(m) = as.character(1:1000000)
microbenchmark(m["3450", 1], m[3450, 1], times=1000)
Unit: microseconds
expr min lq median uq max neval
m["3450", 1] 176465.55 183443.369 185321.5540 185982.0840 522346.477 1000
m[3450, 1] 3.19 3.445 10.7155 14.1545 29.897 1000
我绝对需要使用行名来读取我的矩阵元素。如何提高性能?
更新
我添加了来自 Geoffrey answer 和 subset() 的基准测试结果。我不知道为什么但是 subset() 具有更好的只读性能([[]] 允许分配,subset() 不允许):
microbenchmark(m["3450", 1], m[["3450", 1]], m[3450, 1], .subset(m, 1)["3450"], .subset(m, 1)[3450], times=1000)
Unit: microseconds
expr min lq median uq max neval
m["3450", 1] 176667.252 180197.435 181969.2900 185090.9155 254075.814 1000
m[["3450", 1]] 144.732 145.341 151.1440 191.9960 1096.183 1000
m[3450, 1] 2.900 3.290 4.4400 6.5025 22.391 1000
.subset(m, 1)["3450"] 2.704 3.140 4.1285 14.8740 43.134 1000
.subset(m, 1)[3450] 2.460 2.815 3.2680 13.0300 38.105 1000
【问题讨论】:
-
为什么这对您有限制?为什么您需要如此频繁地进行子集化,这很重要?为什么需要通过行名重复访问矩阵元素?也许,你应该重新考虑你的算法?
-
来自
?.subset:except that methods dispatch does not take place。这就是它更快的原因。
标签: r matrix microbenchmark