/* ex: set ts=2 et: */ /** * * steven came into ##c and wanted to know if there was a way of "optimizing" the logic: * if (a == -1 && b == -1) ... * * 268435456 iterations: * neg1_obvious: 1.178 secs * neg1_crafty: 1.179 secs * neg1_bitwise: 1.009 secs * */ #include #include #include #define N_TIMES (1 << 28) static void speed(const char *name, int (*f)(int, int)) { struct timeval tv[2]; double d[2]; unsigned n = N_TIMES; printf("%20s: ", name); gettimeofday(tv, NULL); while (n--) f(n, n); gettimeofday(tv + 1, NULL); d[0] = (tv[0].tv_sec * 1000000) + tv[0].tv_usec; d[1] = (tv[1].tv_sec * 1000000) + tv[1].tv_usec; printf(" %.3f secs\n", (d[1] - d[0]) / 1000000); } static int neg1_obvious(int a, int b) { return -1 == a && -1 == b; } static int neg1_crafty(int a, int b) { return -1 == a && a == b; } static int neg1_bitwise(int a, int b) { return -1 == (-1 & (a & b)); } int main(void) { printf("%u iterations:\n", N_TIMES); speed("neg1_obvious", neg1_obvious); speed("neg1_crafty", neg1_crafty); speed("neg1_bitwise", neg1_bitwise); return 0; }