2

こんにちは、このstd::vector<std::string>ような日付時刻が含まれています。と2011-03-23T12:23:32.123の 2 つのベクトルを生成したいと思います。int 20110323122332123

私はC++Rcpp というライブラリを使用しています (これは実際には問題ではないと思いますが、わからないのでRcppタグを付けます)

私は仕事をするこれをしましたが、それはかなり遅いです、どうすればこれをスピードアップできますか?

Rcpp::List datetimeToInt(vector<string> datetimes){

    const int N=datetimes.size();
    Rcpp::IntegerVector date(N);  //please consider those as std::vector<int>
    Rcpp::IntegerVector time(N);

    //this is what I want to speed up
    for(int i=0; i<N; ++i){
        datetimes[i].erase(std::remove_if(datetimes[i].begin(), datetimes[i].end(), not1(ptr_fun(::isdigit))), datetimes[i].end());
        date[i] = atoi(datetimes[i].substr(0,8).c_str());
        time[i] = atoi(datetimes[i].substr(8,12).c_str());
    }

    return Rcpp::List::create(_["date"]=date, _["time"]=time); 
}
4

3 に答える 3

1

非常によく似た動作をする Simonのfasttimeパッケージ ( rforge.net で入手可能) を参照してください。

文字列操作のみを使用し、日付の解析を行わずに、UTC 時間であると想定される ISO 日時文字列 (ただし、'T' 区切り文字を使用) を分割します。そこでの私のニーズに合っているので、私はいつもそれを使っていました。

注意として、いつ STL コンテナーを使用するか、およびいつ Rcpp コンテナーを使用するかについて、より慎重に検討することをお勧めします。

最後に、R、C++、および Rcpp にある適切な日付型を使用できる場合は、日付の演算または比較に string または int を使用しないでください。

于 2013-06-19T13:15:32.633 に答える
1

を使用してstd::vector<std::string>、文字列のコピーを作成する必要があります。これは時間の無駄です。CharacterVectorデータを直接操作するため、コピーを作成する必要のないを使用する必要があります。

// [[Rcpp::export]]
List datetimeToInt2(CharacterVector datetimes){

    const int N=datetimes.size();
    IntegerVector date(N); 
    IntegerVector time(N);
    std::string current ; 

    //this is what I want to speed up
    for(int i=0; i<N; ++i){
        current = datetimes[i] ;
        current.erase(std::remove_if(current.begin(), current.end(), std::not1(std::ptr_fun(::isdigit))), current.end());
        date[i] = atoi(current.substr(0,8).c_str());
        time[i] = atoi(current.substr(8,12).c_str());
    }

    return List::create(_["date"]=date, _["time"]=time); 
}        

これを測定しましょう:

> dates <- rep("2011-03-23T12:23:32.123", 1e+05)
> system.time(res1 <- datetimeToInt(dates))
    user  system elapsed
   0.081   0.006   0.087
> system.time(res2 <- datetimeToInt2(dates))
    user  system elapsed
   0.044   0.000   0.044
> identical(res1, res2)
[1] TRUE    
于 2013-06-19T10:58:29.153 に答える