Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created September 24, 2023 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttsugriy/f603a79f61d11720c14dd8c5923d471c to your computer and use it in GitHub Desktop.
Save ttsugriy/f603a79f61d11720c14dd8c5923d471c to your computer and use it in GitHub Desktop.
strncmp vs strcmp benchmark
#include <string.h>
/* Compare no more than N characters of S1 and S2,
returning less than, equal to or greater than zero
if S1 is lexicographically less than, equal to or
greater than S2. */
int
STRNCMP (const char *s1, const char *s2, size_t n)
{
unsigned char c1 = '\0';
unsigned char c2 = '\0';
if (n >= 4)
{
size_t n4 = n >> 2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
} while (--n4 > 0);
n &= 3;
}
while (n > 0)
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
n--;
}
return c1 - c2;
}
/* Compare S1 and S2, returning less than, equal to or
greater than zero if S1 is lexicographically less than,
equal to or greater than S2. */
int
STRCMP (const char *p1, const char *p2)
{
const unsigned char *s1 = (const unsigned char *) p1;
const unsigned char *s2 = (const unsigned char *) p2;
unsigned char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
char * name = "perf";
static void BH_strncmp(benchmark::State& state) {
for (auto _ : state) {
benchmark::DoNotOptimize(STRNCMP(name, "perf", 5));
}
}
BENCHMARK(BH_strncmp);
static void BH_strcmp(benchmark::State& state) {
for (auto _ : state) {
benchmark::DoNotOptimize(STRCMP(name, "perf"));
}
}
BENCHMARK(BH_strcmp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment