Skip to content

Instantly share code, notes, and snippets.

@alecbz
Created September 5, 2012 03:11
Show Gist options
  • Save alecbz/3629710 to your computer and use it in GitHub Desktop.
Save alecbz/3629710 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
unsigned int countOnes(unsigned int input) {
// lab answer here
}
unsigned int countOnesSlow(unsigned int input) {
int count = 0;
while (input) {
count += (input & 01);
input >>= 1;
}
return count;
}
#define DATA_SIZE 100000000
int main() {
srand(time(NULL));
unsigned int* data;
data = calloc(DATA_SIZE, sizeof(unsigned int));
unsigned long i;
for (i = 0; i < DATA_SIZE; ++i) {
data[i] = rand();
}
clock_t start, end;
start = clock();
for (i = 0; i < DATA_SIZE; ++i) {
countOnesSlow(data[i]);
}
end = clock();
printf("countOnesSlow:\t%f sec\n", ((float)(end - start))/CLOCKS_PER_SEC);
start = clock();
for (i = 0; i < DATA_SIZE; ++i) {
countOnes(data[i]);
}
end = clock();
printf("countOnes:\t%f sec\n", ((float)(end - start))/CLOCKS_PER_SEC);
for (i = 0; i < DATA_SIZE; ++i) {
int a = countOnes(data[i]);
int b = countOnesSlow(data[i]);
if (a != b) {
fprintf(stderr, "for %d: expected %d, got %d\n", data[i], a, b);
return 1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment