[Rcpp-devel] use of auxiliary functions
Dirk Eddelbuettel
edd at debian.org
Thu Aug 12 21:53:14 CEST 2010
On 12 August 2010 at 20:59, baptiste auguie wrote:
| Point well taken, l'll try to use const and const& wherever appropriate.
I am coming to this late (sorry, too much other stuff going on...) but I had
meant to illustrate the good advise provided by Davor and Romain. So here is
a stylized Armadillo examples -- not involving SEXPs as these really are
pointers which muddles everything. So here I simply create a matrix and
ship it to two functions: one uses const ref , one uses copy:
edd at max:~/src/progs/C++$ ./const_ref_vs_copy_cost
t0: 2010-Aug-12 14:45:04.526660
t1: 2010-Aug-12 14:45:04.526731 00:00:00.000071
t2: 2010-Aug-12 14:45:05.054273 00:00:00.527542
So 71 microsecs versus 527 millisecs. This uses Boost which gives us nice
granularity of time on Linux. On another OS your mileage may vary. The Emacs
compile-command "works for me" with Boost and Armadillo in standard
places. Adjust as necessary.
And for what it is worth, "const whenever possible" is item #3 in "Effective
C++" by Meyers, a book Romain and I both cherish.
Cheers, Dirk
// -*- compile-command: "g++ -s -O3 -Wall -pedantic -pipe -o const_ref_vs_copy_cost const_ref_vs_copy_cost.cpp -lboost_date_time-mt" -*-
#include <boost/date_time/posix_time/posix_time.hpp>
#include <armadillo>
#include <iostream>
using namespace boost::posix_time; // boost timers
using namespace boost::gregorian;
using namespace arma;
double doSomeMindlessWork_const_ref(const mat & m) {
int n = m.n_rows;
int k = m.n_cols;
return m(0,0) + m(n-1, k-1);
}
double doSomeMindlessWork_copy(mat m) {
int n = m.n_rows;
int k = m.n_cols;
return m(0,0) + m(n-1, k-1);
}
int main() {
const int n = 10000;
mat m = mat(n, n);
ptime t0 = microsec_clock::local_time();
doSomeMindlessWork_const_ref(m);
ptime t1 = microsec_clock::local_time();
doSomeMindlessWork_copy(m);
ptime t2 = microsec_clock::local_time();
std::cout << "t0: " << to_simple_string(t0) << "\n"
<< "t1: " << to_simple_string(t1) << " " << to_simple_string(t1-t0) << "\n"
<< "t2: " << to_simple_string(t2) << " " << to_simple_string(t2-t1) << "\n"
<< std::endl;
return 0;
}
--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
More information about the Rcpp-devel
mailing list