Skip to content

Instantly share code, notes, and snippets.

@wmorgan
Created January 15, 2009 21:36
Show Gist options
  • Save wmorgan/47645 to your computer and use it in GitHub Desktop.
Save wmorgan/47645 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#define SIZE (1024 * 1024 * 500)
#define TIMES 10000000
#define START_TIMER() { \
struct timeval startt, endt; \
gettimeofday(&startt, NULL); \
#define END_TIMER(name) \
gettimeofday(&endt, NULL); \
printf("%20s: %8luus\n", name, 1000000 * (endt.tv_sec - startt.tv_sec) + (endt.tv_usec - startt.tv_usec)); \
}
typedef struct {
unsigned char type;
union {
int i;
double d;
void* p;
} val;
} struct1;
// just to confirm that adding more doesn't increase the struct size
typedef struct {
unsigned char type;
unsigned char flags;
union {
char c;
int i;
double d;
void* p;
} val;
} struct2;
// what if we use four-byte offsets, at the cost of an additional add
// every time we dereference? i don't know if this is even doable.
typedef struct {
unsigned char type;
unsigned char flags;
union {
char c;
int i;
int offset;
} val;
} struct3;
int main(int argc, char* argv[]) {
int i;
void* mem;
printf("sizeof(int) = %lu\n", sizeof(int));
printf("sizeof(int*) = %lu\n", sizeof(int*));
printf("sizeof(struct1) = %lu\n", sizeof(struct1));
printf("sizeof(struct2) = %lu\n", sizeof(struct2));
printf("sizeof(struct3) = %lu\n", sizeof(struct3));
START_TIMER();
mem = malloc(SIZE);
END_TIMER("allocate");
// just curious how long this takes
START_TIMER();
memset(mem, 9, SIZE);
END_TIMER("memset");
START_TIMER();
for(i = 0; i < TIMES; i++) {
unsigned int start = rand() % (SIZE / sizeof(struct1));
unsigned int end = rand() % (SIZE / sizeof(struct1));
}
END_TIMER("empty loop");
printf("can fit %lu struct1's (size %lu)\n", SIZE / sizeof(struct1), sizeof(struct1));
START_TIMER();
for(i = 0; i < TIMES; i++) {
unsigned int start = rand() % (SIZE / sizeof(struct1));
unsigned int end = rand() % (SIZE / sizeof(struct1));
*((struct1*)mem + start) = *((struct1*)mem + end);
}
END_TIMER("copying struct1s");
printf("can fit %lu struct3's (size %lu)\n", SIZE / sizeof(struct3), sizeof(struct3));
START_TIMER();
for(i = 0; i < TIMES; i++) {
unsigned int start = rand() % (SIZE / sizeof(struct3));
unsigned int end = rand() % (SIZE / sizeof(struct3));
*((struct3*)mem + start) = *((struct3*)mem + end);
}
END_TIMER("copying struct3s");
printf("can fit %lu int's (size %lu)\n", SIZE / sizeof(int), sizeof(int));
START_TIMER();
for(i = 0; i < TIMES; i++) {
unsigned int start = rand() % (SIZE / sizeof(int));
unsigned int end = rand() % (SIZE / sizeof(int));
*((int*)mem + start) = *((int*)mem + end);
}
END_TIMER("copying ints");
// sanity check
START_TIMER();
sleep(2);
END_TIMER("sleep(2)");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment