我正在使用 Rcpp 来分析 XTS 数据,并使用以下 rcpp 代码获取其时间索引:
#include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
DatetimeVector xtsIndex(NumericMatrix X)
{
DatetimeVector v(NumericVector(X.attr("index")));
return v;
}
DatetimeVector tmpindexDaily = xtsIndex(askDailymat); // Get xts index to Rcpp vector
事实证明,这种转换需要 2 毫秒才能在某组数据上执行,因为我只需要时间索引,没有这段代码,它只需要不到 100 微秒。有没有办法更好地优化转换或完全避免转换。
最好
只使用具有适当类属性的NumericVector
。 这是我几周前在另一个项目中使用的快速一次性功能:
Rcpp::NumericVector createPOSIXtVector(const std::vector<double> & ticks,
const std::string tz) {
Rcpp::NumericVector pt(ticks.begin(), ticks.end());
pt.attr("class") = Rcpp::CharacterVector::create("POSIXct", "POSIXt");
pt.attr("tzone") = tz;
return pt;
}
您可以从其他容器、矩阵列、向量等类似方式开始。这可以保存double
值,并利用时间(POSIXct
)时间实际上是自纪元以来的小数double
的事实。 在这里,我们从另一个 API 获得了std::vector<double>
,因此转换非常便宜。