Skip to content

Instantly share code, notes, and snippets.

@SteveBronder
Created December 10, 2020 00:43
Show Gist options
  • Save SteveBronder/84ba7d4bfb0f5ded4289f3b702f6b940 to your computer and use it in GitHub Desktop.
Save SteveBronder/84ba7d4bfb0f5ded4289f3b702f6b940 to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <stdexcept>
#include <sstream>
#include <string>
#include <typeinfo>
#include <sstream>
#include <stdexcept>
#include <benchmark/benchmark.h>
#ifdef __GNUC__
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define STAN_STRONG_INLINE __attribute__((always_inline)) inline
#define STAN_COLD_PATH __attribute__((noinline, cold))
#else
#define likely(x) (x)
#define unlikely(x) (x)
#define STAN_STRONG_INLINE
#define STAN_COLD_PATH
#endif
inline void out_of_range(const char* function, int max, int index,
const char* msg1 = "", const char* msg2 = "") {
std::ostringstream message;
message << function << ": accessing element out of range. "
<< "index " << index << " out of range; ";
if (max == 0) {
message << "container is empty and cannot be indexed" << msg1 << msg2;
} else {
message << "expecting index to be between " << 1
<< " and " << 0 + max << msg1 << msg2;
}
throw std::out_of_range(message.str());
}
inline void check_range(const char* function,
const char* name, int max,
int index, int nested_level, const char* error_msg) {
if (unlikely(index > max)) {
[&]() STAN_COLD_PATH {
std::stringstream msg;
msg << "; index position = " << nested_level;
std::string msg_str(msg.str());
out_of_range(function, max, index, msg_str.c_str(), error_msg);
}();
}
return;
}
static void check_range_bench(benchmark::State& state) {
for(auto _ : state) {
for (int i = 0; i < state.range(0); ++i) {
int foo = state.range(0);
check_range("blah", "blah", foo, i, 0, "ANON");
}
}
}
inline void check_range2(const char* function, const char* name, int max,
int index, int nested_level, const char* error_msg) {
if (index < max) {
return;
}
std::stringstream msg;
msg << "; index position = " << nested_level;
std::string msg_str(msg.str());
out_of_range(function, max, index, msg_str.c_str(), error_msg);
}
static void check_range2_bench(benchmark::State& state) {
for(auto _ : state) {
for (int i = 0; i < state.range(0); ++i) {
int foo = state.range(0);
check_range2("blah", "blah", foo, i, 0, "ANON");
}
}
}
constexpr int start_val = 2;
constexpr int end_val = 100000;
BENCHMARK(check_range_bench)->RangeMultiplier(2)->Range(start_val, end_val);
BENCHMARK(check_range2_bench)->RangeMultiplier(2)->Range(start_val, end_val);
BENCHMARK_MAIN();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment