I made a function to add two numbers together using bit manipulation. I started off writing the function add_a, then made a modified version add_b.
add_a seems to be 10-15% faster than add_b. The thing is is that in add_b I removed a variable, and a reset and a copy from in the loop. So why does it appear slower?
Code:#include <stdio.h> #include <limits.h> #include <stdlib.h> #include <time.h> #define Uint8 unsigned char Uint8 add_a(Uint8 a, Uint8 b) { static Uint8 i, num = 0; static Uint8 result = 0; static Uint8 carry = 0; static Uint8 bit = 1; for(i=0; i<CHAR_BIT; i++) { num = 0; if(a & bit) num++; if(b & bit) num++; if(carry) num++; if(num & 1) result |= bit; carry = (num & 2); bit <<= 1; } return result; } Uint8 add_b(Uint8 a, Uint8 b) { static Uint8 i, num = 0; static Uint8 result = 0; static Uint8 bit = 1; for(i=0; i<CHAR_BIT; i++) { if(a & bit)num++; if(b & bit)num++; if(num & 1) result |= bit; num = (num & 2) ? 1: 0; bit <<= 1; } return result; } Uint8 add_c(Uint8 a, Uint8 b) { static Uint8 i, num = 0; static Uint8 result = 0; static Uint8 bit = 1; for(i=0; i<CHAR_BIT; i++) { if(a & bit) if(b & bit) num += 2; else num += 1; else if(b & bit) num += 1; if(num & 1) result |= bit; num = (num & 2) ? 1: 0; bit <<= 1; } return result; } void test(int x, int y) { unsigned start = clock(), i; for(i=0; i<50000000; i++) add_a(x, y); printf("A: <Time %u> <Result %u>\n", clock()-start, add_a(x, y)); start = clock(); for(i=0; i<50000000; i++) add_b(x, y); printf("B: <Time %u> <Result %u>\n", clock()-start, add_b(x, y)); start = clock(); for(i=0; i<50000000; i++) add_c(x, y); printf("C: <Time %u> <Result %u>\n", clock()-start, add_c(x, y)); } int main() { Uint8 a = 102; Uint8 b = 57; test(a, b); getchar(); }

