#include #include #include #include #include #include #include #define NOF_TESTS 1024*1024 #define STR_LEN 19 typedef char fixed_string[STR_LEN+1]; static const char * gen_str() { static fixed_string s; for (size_t i = 0; i < sizeof(fixed_string)-1; ++i) { s[i] = rand() % 25 + 65; } s[sizeof(s)-1] = '\0'; return s; } ////////////////////////////////////////////////////////////////////////////// // BEGIN memcmp.c ////////////////////////////////////////////////////////////////////////////// #define IS_ALIGNED(x) (((size_t)(x) & sizeof(size_t)-1) == 0) /* * Compare memory regions. */ int my_memcmp(const void *s1, const void *s2, size_t n) { if (n == 0) return (0); /* If the two args are aligned, compare them one word at a time. */ const size_t *p1 = s1, *p2 = s2; if (((size_t)s1 & (sizeof(size_t) - 1)) == 0 && ((size_t)s2 & (sizeof(size_t) - 1)) == 0) { while (n >= sizeof(size_t) && *p1 == *p2) { ++p1; ++p2; n -= sizeof(size_t); } if (n == 0) return (0); } /* Usual byte-by-byte comparison. */ const char *c1 = (const char *)p1, *c2 = (const char *)p2; while (--n > 0 && *c1 == *c2) { ++c1; ++c2; } return (*c1 - *c2); } ////////////////////////////////////////////////////////////////////////////// // END memcmp.c ////////////////////////////////////////////////////////////////////////////// int main() { fixed_string * c1 = malloc(NOF_TESTS * sizeof(*c1)); fixed_string * c2 = malloc(NOF_TESTS * sizeof(*c2)); int * d1 = malloc(NOF_TESTS * sizeof(*d1)); int * d2 = malloc(NOF_TESTS * sizeof(*d2)); for (size_t i = 0; i < NOF_TESTS; ++i) { strcpy(c1[i], gen_str()); strcpy(c2[i], gen_str()); } struct timeval start, end; gettimeofday(&start, NULL); for (size_t i = 0; i < NOF_TESTS; ++i) { d1[i] = memcmp(c1[i], c2[i], STR_LEN); } gettimeofday(&end, NULL); printf("theirs: %lu\n", ((end.tv_sec - start.tv_sec)*1000000L + end.tv_usec) - start.tv_usec); gettimeofday(&start, NULL); for (size_t i = 0; i < NOF_TESTS; ++i) { d2[i] = my_memcmp(c1[i], c2[i], STR_LEN); } gettimeofday(&end, NULL); printf("mine : %lu\n", ((end.tv_sec - start.tv_sec)*1000000L + end.tv_usec) - start.tv_usec); for (size_t i = 0; i < NOF_TESTS; ++i) { assert(d1[i] == d2[i]); } for (size_t t = 1; t < 64; ++t) { size_t * x1 = malloc(t * 2); size_t * x2 = malloc(t * 2); size_t i = 0; for (i = 0; i < t ; ++i) { x1[i] = 'A'; x2[i] = 'A'; } x1[i] = 'A'; x1[i+1] = '\0'; x2[i] = 'B'; x2[i+1] = '\0'; assert(my_memcmp(x1, x2, t) == 0); free(x1); free(x2); } }