Closed renkun-ken closed 3 years ago
You aren't benchmarking the move constructor, you are benchmarking the proxy object, altrep support and unwind protecting.
e.g. see foo4, which is the equivalent if you were trying to benchmark the move constructor.
#include <cpp11.hpp>
using namespace cpp11;
[[cpp11::register]] void fun1(doubles x) {
double* y = REAL(x.data());
for (int i = 0; i < x.size(); i++) {
y[i] = i;
}
}
[[cpp11::register]] void fun2(writable::doubles x) {
double* y = REAL(x.data());
for (int i = 0; i < x.size(); i++) {
y[i] = i;
}
}
[[cpp11::register]] void fun3(doubles x) {
writable::doubles y(std::move(x.data()));
for (int i = 0; i < x.size(); i++) {
y[i] = i;
}
}
[[cpp11::register]] void fun4(doubles x) {
writable::doubles y(std::move(x.data()));
double* y_p = REAL(y);
for (int i = 0; i < x.size(); i++) {
y_p[i] = i;
}
}
cpp11::cpp_source("~/p/cpp11/test.cpp")
x <- rnorm(10000000)
bench::mark(
fun1(x),
fun2(x),
fun3(x),
fun4(x)
)
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 4 x 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 fun1(x) 4.99ms 5.39ms 177. 0B 0
#> 2 fun2(x) 27.59ms 29.23ms 34.2 76.3MB 34.2
#> 3 fun3(x) 9.33ms 9.98ms 96.1 0B 0
#> 4 fun4(x) 4.9ms 5.27ms 182. 0B 0
Created on 2021-07-01 by the reprex package (v2.0.0)
Thanks for pointing it out!
Is it conclusive that if I don't use R's C API, the performance of in-place modifying a vector will inevitably drop to 50% in this case?
I'm experimenting with some approaches of in-place modification of vectors decribed in #42. The following are examples where
fun1
uses R's C API andfun3
usesstd::move()
(as suggested in https://github.com/r-lib/cpp11/issues/42#issuecomment-654385362) whilefun2
copiesx
in the beginning and thus does not modifyx
in place.I expect
fun1
andfun3
to have similar performance and should be both faster thanfun2
. But the following benchmark shows that the move constructor seems quite expensive:I wonder if it is an expected result?