#include #include #include #include #include const size_t N = 1 << 20; char string[N] = {}; struct init { init() { std::random_device device; std::mt19937_64 generator(device()); std::uniform_int_distribution distribution('a', 'z'); auto rng = [&]() { return distribution(generator); }; std::ranges::generate(string, rng); string[N - 1] = 0; } } _; size_t f1(char *str) { size_t len = 0; while (*str++) ++len; return len; } size_t f2(const char *str) { const char *tmp = str; while (*str) ++str; return str - tmp; } size_t f3(const char *str) { const char *tmp = str; while (*tmp++) ; return tmp - str - 1; } size_t f4(const char *str) { if (*str == 0) return 0; else return f4(++str) + 1; } size_t f5(const char *s) { size_t len = 0; for (;;) { unsigned x = *(unsigned *)s; if ((x & 0x000000FF) == 0) return len + 0; if ((x & 0x0000FF00) == 0) return len + 1; if ((x & 0x00FF0000) == 0) return len + 2; if ((x & 0xFF000000) == 0) return len + 3; len += 4, s += 4; } } size_t f6(const char *s) { unsigned x = *(unsigned *)s; if ((x & 0x000000FF) == 0) return 0; if ((x & 0x0000FF00) == 0) return 1; if ((x & 0x00FF0000) == 0) return 2; if ((x & 0xFF000000) == 0) return 3; return f6(s + 4) + 4; } size_t f7(const char *s) { if (*s == 0) [[unlikely]] return 0; else return f7(s + 1) + 1; } size_t f8(const char *s) { if (*s == 0) [[likely]] return 0; else return f8(s + 1) + 1; } size_t fc(char *str) { return strlen(str); } template static void test(benchmark::State &state) { unsigned r = 0; for (auto _: state) benchmark::DoNotOptimize(r = f(string)); state.SetLabel(std::to_string(r)); } BENCHMARK(test); BENCHMARK(test); BENCHMARK(test); BENCHMARK(test); BENCHMARK(test); BENCHMARK(test); BENCHMARK(test); BENCHMARK(test); BENCHMARK(test); BENCHMARK_MAIN();