#define __NO_STRING_INLINES #include #include #include #include #include char s1[] = "abcdefghijklmnopqrstuvwxyz"; void test_my_memcmp (char *s1, int i, int test, int len) { char s2[2 * len + 1]; int j, k; for (k = i; k <= len + 1; k++) for (j = 0; j < len; j++) { memcpy (s2 + j, s1, len + 1); s2[i+j] += test; assert (my_memcmp (s2 + j, s1, k) == (k != i ? test : 0)); } } void speed_libc (char *s1, int i, int test, int len) { char s2[2 * len + 1]; int j, k; for (k = i; k <= len + 1; k++) for (j = 0; j < len; j++) { memcpy (s2 + j, s1, len + 1); s2[i+j] += test; s2[0] = memcmp (s2 + j, s1, k); } } void speed_builtin (char *s1, int i, int test, int len) { char s2[2 * len + 1]; int j, k; for (k = i; k <= len + 1; k++) for (j = 0; j < len; j++) { memcpy (s2 + j, s1, len + 1); s2[i+j] += test; s2[0] = __builtin_memcmp (s2 + j, s1, k); } } void speed_memcmp (char *s1, int i, int test, int len) { char s2[2 * len + 1]; int j, k; for (k = i; k <= len + 1; k++) for (j = 0; j < len; j++) { memcpy (s2 + j, s1, len + 1); s2[i+j] += test; s2[0] = my_memcmp (s2 + j, s1, k); } } void speed_loop (char *s1, int i, int test, int len) { char s2[2 * len + 1]; int j, k; for (k = i; k <= len + 1; k++) for (j = 0; j < len; j++) { memcpy (s2 + j, s1, len + 1); s2[i+j] += test; s2[0] = 0; } } double do_test (int repetitions, void (*test_function) (char *, int, int, int)) { int len = strlen(s1); int i, h; struct rusage r1, r2; getrusage(RUSAGE_SELF, &r1); while (repetitions--) for (h = 0; h < len; h += 5) for (i = h; i < len; i++) { test_function (s1 + h, i - h, -1, len); test_function (s1 + h, i - h, 0, len); test_function (s1 + h, i - h, 1, len); } getrusage(RUSAGE_SELF, &r2); return (r2.ru_utime.tv_sec - r1.ru_utime.tv_sec) + (r2.ru_utime.tv_usec - r1.ru_utime.tv_usec) / 1000000.0; } main(int argc, char **argv) { int repetitions = (argc == 1) ? 100 : atoi(argv[1]); do_test (1, test_my_memcmp); printf ("%d repetitions\n\n", repetitions); printf ("Testing custom memcmp ....."); fflush (stdout); printf (" done, %10.3f seconds\n", do_test (repetitions, speed_memcmp)); printf ("Testing libc memcmp ......."); fflush (stdout); printf (" done, %10.3f seconds\n", do_test (repetitions, speed_libc)); printf ("Testing builtin memcmp ...."); fflush (stdout); printf (" done, %10.3f seconds\n", do_test (repetitions, speed_builtin)); printf ("Testing loop overhead ....."); fflush (stdout); printf (" done, %10.3f seconds\n", do_test (repetitions, speed_loop)); exit (0); }