Skip to content

Commit b48e3a1

Browse files
committed
Add a push_back() + truncate benchmark test
1 parent c619bf2 commit b48e3a1

File tree

4 files changed

+48
-0
lines changed

4 files changed

+48
-0
lines changed

cpp11test/R/cpp11.R

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,3 +231,7 @@ test_destruction_inner <- function() {
231231
test_destruction_outer <- function() {
232232
invisible(.Call(`_cpp11test_test_destruction_outer`))
233233
}
234+
235+
cpp11_push_and_truncate_ <- function(size_sexp) {
236+
.Call(`_cpp11test_cpp11_push_and_truncate_`, size_sexp)
237+
}

cpp11test/bench/truncate.R

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
pkgload::load_all("cpp11test")
2+
3+
bench::press(len = as.integer(10 ^ (0:6)),
4+
{
5+
bench::mark(
6+
cpp11_push_and_truncate_(len),
7+
min_iterations = 100
8+
)
9+
}
10+
)
11+
12+
# Longer benchmark, lots of gc
13+
len <- as.integer(10 ^ 7)
14+
bench::mark(
15+
cpp11_push_and_truncate_(len),
16+
min_iterations = 200
17+
)

cpp11test/src/cpp11.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,13 @@ extern "C" SEXP _cpp11test_test_destruction_outer() {
438438
return R_NilValue;
439439
END_CPP11
440440
}
441+
// truncate.cpp
442+
SEXP cpp11_push_and_truncate_(SEXP size_sexp);
443+
extern "C" SEXP _cpp11test_cpp11_push_and_truncate_(SEXP size_sexp) {
444+
BEGIN_CPP11
445+
return cpp11::as_sexp(cpp11_push_and_truncate_(cpp11::as_cpp<cpp11::decay_t<SEXP>>(size_sexp)));
446+
END_CPP11
447+
}
441448

442449
extern "C" {
443450
/* .Call calls */
@@ -447,6 +454,7 @@ static const R_CallMethodDef CallEntries[] = {
447454
{"_cpp11test_col_sums", (DL_FUNC) &_cpp11test_col_sums, 1},
448455
{"_cpp11test_cpp11_add_vec_for_", (DL_FUNC) &_cpp11test_cpp11_add_vec_for_, 2},
449456
{"_cpp11test_cpp11_insert_", (DL_FUNC) &_cpp11test_cpp11_insert_, 1},
457+
{"_cpp11test_cpp11_push_and_truncate_", (DL_FUNC) &_cpp11test_cpp11_push_and_truncate_, 1},
450458
{"_cpp11test_cpp11_release_", (DL_FUNC) &_cpp11test_cpp11_release_, 1},
451459
{"_cpp11test_cpp11_safe_", (DL_FUNC) &_cpp11test_cpp11_safe_, 1},
452460
{"_cpp11test_data_frame_", (DL_FUNC) &_cpp11test_data_frame_, 0},

cpp11test/src/truncate.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#include "cpp11/doubles.hpp"
2+
3+
[[cpp11::register]] SEXP cpp11_push_and_truncate_(SEXP size_sexp) {
4+
R_xlen_t size = INTEGER(size_sexp)[0];
5+
6+
cpp11::writable::doubles out(size);
7+
8+
// Fill it
9+
for (R_xlen_t i = 0; i < size; ++i) {
10+
out.push_back(0);
11+
}
12+
13+
// Push 1 more past the existing capacity,
14+
// doubling the capacity
15+
out.push_back(0);
16+
17+
// Truncate back to `size + 1` size and return result.
18+
return SEXP(out);
19+
}

0 commit comments

Comments
 (0)