Skip to content

Instantly share code, notes, and snippets.

@qrealka
Created August 27, 2019 15:50
Show Gist options
  • Save qrealka/2add0c5b45f26864e2197e7c8b193bcd to your computer and use it in GitHub Desktop.
Save qrealka/2add0c5b45f26864e2197e7c8b193bcd to your computer and use it in GitHub Desktop.
atoi_fast
#include <cstdlib>
// Andrei Alexandrescu at the C++ and Beyond 2012
class atoi_func
{
public:
atoi_func(): value_() {}
inline int value() const { return value_; }
inline bool operator() (const char *str, size_t len)
{
value_ = 0;
int sign = 1;
if (str[0] == '-') { // handle negative
sign = -1;
++str;
--len;
}
switch (len) { // handle up to 10 digits, assume we're 32-bit
case 10: value_ += (str[len-10] - '0') * 1000000000;
case 9: value_ += (str[len- 9] - '0') * 100000000;
case 8: value_ += (str[len- 8] - '0') * 10000000;
case 7: value_ += (str[len- 7] - '0') * 1000000;
case 6: value_ += (str[len- 6] - '0') * 100000;
case 5: value_ += (str[len- 5] - '0') * 10000;
case 4: value_ += (str[len- 4] - '0') * 1000;
case 3: value_ += (str[len- 3] - '0') * 100;
case 2: value_ += (str[len- 2] - '0') * 10;
case 1: value_ += (str[len- 1] - '0');
value_ *= sign;
return value_ > 0;
default:
return false;
}
}
private:
int value_;
};
static void atoiTest(benchmark::State& state) {
std::string num("-981723944");
for (auto _ : state) {
auto i = atoi(num.c_str());
benchmark::DoNotOptimize(i);
}
}
// Register the function as a benchmark
BENCHMARK(atoiTest);
static void alexTest(benchmark::State& state) {
std::string num("-981723944");
atoi_func parse;
for (auto _ : state) {
auto i = parse(num.c_str(), num.length());
benchmark::DoNotOptimize(i);
}
}
BENCHMARK(alexTest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment