Skip to content

Commit 7b8450f

Browse files
committed
Try to mask array length from compiler to inhibit elision of the bounds check
Signed-off-by: Larry Gritz <lg@larrygritz.com>
1 parent a591e1a commit 7b8450f

1 file changed

Lines changed: 12 additions & 4 deletions

File tree

src/libutil/span_test.cpp

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ using namespace OIIO;
1919
static int iterations = 100000;
2020
static int ntrials = 5;
2121

22+
// Intentionally not static so the compiler can't optimize away its value
23+
int Nlen_unknown = 0;
24+
25+
2226

2327
static void
2428
getargs(int argc, char* argv[])
@@ -33,6 +37,9 @@ getargs(int argc, char* argv[])
3337
iterations));
3438
ap.arg("--trials %d", &ntrials).help("Number of trials");
3539

40+
// Fake option to hide from compiler how big it will be
41+
ap.arg("--unknown %d", &Nlen_unknown).hidden();
42+
3643
ap.parse_args(argc, (const char**)argv);
3744
}
3845

@@ -489,27 +496,28 @@ benchmark_span()
489496
// bench.work(N);
490497
std::array<float, N> fstdarr;
491498
std::fill(fstdarr.begin(), fstdarr.end(), 1.0f);
499+
size_t Nlen = Nlen_unknown ? size_t(Nlen_unknown) : N;
492500
bench("pointer operator[]", [&]() {
493501
float* fptr(fstdarr.data());
494502
float t = 0.0f;
495-
for (size_t i = 0; i < N; ++i)
503+
for (size_t i = 0; i < Nlen; ++i)
496504
DoNotOptimize(t += fptr[i]);
497505
});
498506
bench("std::array operator[]", [&]() {
499507
float t = 0.0f;
500-
for (size_t i = 0; i < N; ++i)
508+
for (size_t i = 0; i < Nlen; ++i)
501509
DoNotOptimize(t += fstdarr[i]);
502510
});
503511
bench("span operator[]", [&]() {
504512
span<float> fspan(fstdarr);
505513
float t = 0.0f;
506-
for (size_t i = 0; i < N; ++i)
514+
for (size_t i = 0; i < Nlen; ++i)
507515
DoNotOptimize(t += fspan[i]);
508516
});
509517
bench("span unsafe indexing", [&]() {
510518
span<float> fspan(fstdarr);
511519
float t = 0.0f;
512-
for (size_t i = 0; i < N; ++i)
520+
for (size_t i = 0; i < Nlen; ++i)
513521
DoNotOptimize(t += fspan.data()[i]);
514522
});
515523
bench("span range", [&]() {

0 commit comments

Comments
 (0)