Skip to content

Instantly share code, notes, and snippets.

@michael-grunder
Last active August 29, 2015 14:08
Show Gist options
  • Save michael-grunder/63e0f9eb924443c8ba3c to your computer and use it in GitHub Desktop.
Save michael-grunder/63e0f9eb924443c8ba3c to your computer and use it in GitHub Desktop.
silly dictNextPower test
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <math.h>
#define DICT_HT_INITIAL_SIZE 4
static unsigned long _dictNextPowerNew(unsigned long size)
{
if (size >= LONG_MAX) return LONG_MAX;
if (size <= DICT_HT_INITIAL_SIZE){
return DICT_HT_INITIAL_SIZE;
}
else{
while(size & (size-1)){
size |= size-1;
size++;
}
return size;
}
}
static unsigned long _dictNextPowerOld(unsigned long size)
{
unsigned long i = DICT_HT_INITIAL_SIZE;
if (size >= LONG_MAX) return LONG_MAX;
while(1) {
if (i >= size)
return i;
i *= 2;
}
}
int main(int argc, const char **argv) {
unsigned long n2, i, j;
unsigned long long v;
double tm1, tm2, tmnew, tmold;
if (argc < 2) {
fprintf(stderr, "Pass iterations!\n");
exit(1);
}
long n = strtol(argv[1], NULL, 10);
for (i = 1000000; i <= n; i += 500000) {
n2 = 3;
v = 0;
tm1 = clock();
for (j = 0; j < i; j++) {
v += _dictNextPowerOld(n2);
if (v >= LONG_MAX) {
n2 = 3;
} else {
n2++;
}
}
tm2 = clock();
tmold = ((double)tm2-tm1)/CLOCKS_PER_SEC;
n2 = 3;
v = 0;
tm1 = clock();
for (j = 0; j < i; j++) {
v += _dictNextPowerNew(n2);
if (v >= LONG_MAX) {
n2 = 3;
} else {
n2++;
}
}
tm2 = clock();
tmnew = ((double)tm2 - tm1)/CLOCKS_PER_SEC;
printf("%lu => old=%f; new=%f [%s faster by %f]\n", i, tmold, tmnew,
tmold > tmnew ? "new" : "old", fabs(tmold-tmnew));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment