#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct unaligned {
char a;
int b;
} __attribute__((packed));
struct aligned {
int b;
char a;
} __attribute__((packed));
int unaligned (struct unaligned *f) {
f->a = (char)rand();
return f->b;
}
int aligned (struct aligned *f) {
int b = f->b;
f->a = (char)rand();
return b;
}
int main (void) {
struct aligned a;
struct unaligned u;
struct timespec s, e;
double delta;
clock_gettime(CLOCK_MONOTONIC, &s);
e.tv_sec = s.tv_sec;
while (s.tv_sec == e.tv_sec)
clock_gettime(CLOCK_MONOTONIC, &e);
clock_gettime(CLOCK_MONOTONIC, &s);
int i = 0;
for (e.tv_sec = s.tv_sec; e.tv_sec == s.tv_sec; i++) {
u.b = (int)rand();
printf("%d\n", unaligned(&u));
clock_gettime(CLOCK_MONOTONIC, &e);
}
delta = (double)(e.tv_sec - s.tv_sec) + (double)(e.tv_nsec - s.tv_nsec) / 1000000;
fprintf(stderr, "unaligned = %d iterations in %lf seconds (%lf iterations per second)\n",
i, delta, i / delta);
clock_gettime(CLOCK_MONOTONIC, &s);
e.tv_sec = s.tv_sec;
while (s.tv_sec == e.tv_sec)
clock_gettime(CLOCK_MONOTONIC, &e);
clock_gettime(CLOCK_MONOTONIC, &s);
i = 0;
for (e.tv_sec = s.tv_sec; e.tv_sec == s.tv_sec; i++) {
a.b = (int)rand();
printf("%d\n", aligned(&a));
clock_gettime(CLOCK_MONOTONIC, &e);
}
delta = (double)(e.tv_sec - s.tv_sec) + (double)(e.tv_nsec - s.tv_nsec) / 1000000;
fprintf(stderr, "aligned = %d iterations in %lf seconds (%f iterations per second)\n",
i, delta, i / delta);
return 0;
}