Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Armadillo's print() method and cout are inconsistent in order when called from Rcpp

Lately, I've been using RcppArmadillo, but I've noticed some inconsistencies in the print order of certain objects. Particularly, when using cout and print(). Sometimes, print() will be printed first, then cout; and other times it's the other way around.

I do not understand exactly why this is happening. I suppose cout and print() are called asynchronously and hence the difference in order, but why is this happening? And how can it be prevented?

Example

If I have the following test_order.cpp file

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace arma;


// [[Rcpp::export]]
int test(int n){

  cout << "Print 1\n";
  arma::mat X(n, n);
  cout << "Print 2\n";
  X.print();
  cout << "Print 3\n";

  return 1;

}

And call it from R like this

library(Rcpp)

sourceCpp("test_order.cpp")

test(3)

I get different results when printing. Three different results are the following:

> test(3)
  2.1220e-314            0  6.9531e-310Print 1
Print 2

  2.3044e-314  6.9275e-310  6.9532e-310
  2.1916e-314  2.1916e-314  2.2718e-314
Print 3
[1] 1
> test(3)
  Print 1
Print 2
6.9531e-310  2.3044e-314  4.9407e-324
  6.9532e-310  2.1916e-314  4.9407e-324
            0  6.9275e-310  4.9407e-324
Print 3
[1] 1

> test(3)
  6.9531e-310  2.3044e-314  4.9407e-324
  6.9532e-310  2.1916e-314  4.9407e-324
            0  6.9275e-310  4.9407e-324Print 1
Print 2

[1]Print 3
 1
like image 575
Mario Becerra Avatar asked Nov 26 '25 03:11

Mario Becerra


1 Answers

Based on Roland's and Dirk's comments, as well as Dirk's book and this Rcpp article, the solution is to use Rcout instead of cout and print().

According to Dirk's book:

Because R provides the “shell” around our statistical computing, programs need to synchronize their (printed) output with R which uses its own buffering.

In addition that CRAN maintainers flag code that includes std::cout.

So the test_order.cpp file should be like this:

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace arma;


// [[Rcpp::export]]
int test(int n){
    Rcout << "Print 1\n";
    arma::mat X(n, n);
    Rcout << "Print 2\n";
    Rcout << X << "\n";
    Rcout << "Print 3\n";

    return 1;
}
like image 184
Mario Becerra Avatar answered Nov 27 '25 16:11

Mario Becerra