Skip to content

Instantly share code, notes, and snippets.

@mkevac
Created June 29, 2012 14:27
Show Gist options
  • Save mkevac/3018264 to your computer and use it in GitHub Desktop.
Save mkevac/3018264 to your computer and use it in GitHub Desktop.
Speed test
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#define HOWMUCH 100000000
#define RANDOMBITS 4
static uint64_t stats[32];
static uint64_t stats2[32];
static uint32_t flags[HOWMUCH];
int main()
{
time_t start;
/* generate flags */
printf("generating flags... ");
start = time(NULL);
for (uint64_t i = 0; i < HOWMUCH; i++) {
/* create random flag */
for (uint32_t j = 0; j < RANDOMBITS; j++) {
flags[i] |= 1 << (random() % 32);
}
}
printf("%ld s\n", time(NULL) - start);
printf("using cycle... ");
start = time(NULL);
for (uint64_t i = 0; i < HOWMUCH; i++) {
for (int x = 0; x < 32; x++) {
if (flags[i] & (1 << x)) {
stats[x]++;
}
}
}
printf("%ld s\n", time(NULL) - start);
for (int x = 0; x < 32; x++) {
printf("%ld ", stats[x]);
}
printf("\n");
printf("using builtin... ");
start = time(NULL);
for (uint64_t i = 0; i < HOWMUCH; i++) {
uint32_t flag = flags[i];
int offset = 0;
while (flag > 0) {
int zeroes = __builtin_ctzl(flag);
int moveby = zeroes+1;
stats2[offset + zeroes]++;
if (moveby == 32) {
flag = 0;
} else {
flag >>= moveby;
offset += moveby;
}
}
}
printf("%ld s\n", time(NULL) - start);
for (int x = 0; x < 32; x++) {
printf("%ld ", stats2[x]);
}
printf("\n");
for (int x = 0; x < 32; x++) {
if (stats[x] != stats2[x]) {
printf("%i bit NOT SAME (%ld != %ld)\n", x, stats[x], stats2[x]);
return 0;
}
}
printf("SAME\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment