Consider the following functions foo
and bar
(differs only in printing warning) and their R equivalents fooR
and barR
:
cppFunction(' void foo () { int i = 0; while (i < 1e3) { i++; } return; }') cppFunction(' void bar () { int i = 0; while (i < 1e3) { i++; Rcpp::warning("hello world!"); } return; }') fooR <- function() { i = 0; while (i < 1e3) { i = i+1; } } barR <- function() { i = 0; while (i < 1e3) { i = i+1; warning("hello world!") } }
Obviously, printing warnings makes function slower, but the difference between R and Rcpp is huge (200 times slower vs 5000 times slower!):
> benchmark(foo(), bar()) test replications elapsed relative user.self sys.self user.child sys.child 2 bar() 100 5.156 5156 5.156 0 0 0 1 foo() 100 0.001 1 0.000 0 0 0 There were 50 or more warnings (use warnings() to see the first 50) > benchmark(fooR(), barR()) test replications elapsed relative user.self sys.self user.child sys.child 2 barR() 100 11.102 213.5 11.104 0 0 0 1 fooR() 100 0.052 1.0 0.052 0 0 0 There were 50 or more warnings (use warnings() to see the first 50)
Why is it so? Can it be prevented?