/* * costs.c -- calculate costs of strncmp against memmove * * Dmitri Tikhonov * February 8, 2006 */ #include #include #include #include #include #include #include #include #include #define STRLEN 40 #define MEMLEN (1 << 10) static void usage (const char *progname) { fprintf(stderr, "Usage: %s repetitions\n", progname); return; } int main (int argc, char **argv) { int i, n, fd, diff; struct timeval t[2]; struct timezone dummy; /* not used */ char a[STRLEN], b[STRLEN]; char *data; if (argc < 2) { usage(*argv); exit(1); } n = atoi(argv[1]); if (n < 0) { fprintf(stderr, "argument should be a positive integer\n"); exit(2); } /* Get two random strings from /dev/random */ if (-1 == (fd = open("/dev/random", O_RDONLY))) { perror("Cannot open /dev/random"); exit(3); } read(fd, a, STRLEN); read(fd, b, STRLEN); close(fd); gettimeofday(&t[0], &dummy); for (i = 0; i < n; ++i) strncmp(a, b, STRLEN); gettimeofday(&t[1], &dummy); diff = 1000000 * (t[1].tv_sec - t[0].tv_sec) + (t[1].tv_usec - t[0].tv_usec); printf("Average cost of strncmp: %.2f nanoseconds\n", (float) 1000 * diff / n); data = malloc(MEMLEN + 1); gettimeofday(&t[0], &dummy); for (i = 0; i < n; ++i) memmove(data + 1, data, MEMLEN); gettimeofday(&t[1], &dummy); diff = 1000000 * (t[1].tv_sec - t[0].tv_sec) + (t[1].tv_usec - t[0].tv_usec); printf("Average cost of memmove: %.2f nanoseconds\n", (float) 1000 * diff / n); exit(0); }