#define SIZE 10000000
int x[SIZE];
int y[SIZE];
int i;
int *p1, *p2;
void TestSubscripts(void)
{
for (i = 0; i < SIZE; i++)
x[i] = y[i];
}
void TestPointers1(void)
{
for (p1 = x, p2 = y; p1 - x < SIZE; )
*p1++ = *p2++;
}
void TestPointers2(void)
{
for (p1 = x, p2 = y; p1 < &x[SIZE]; )
*p1++ = *p2++;
}
void TestPointers3(void)
{
register int *p1, *p2;
for (p1 = x, p2 = y; p1 < &x[SIZE]; )
*p1++ = *p2++;
}
The "driver" code:
void TestTimings(void)
{
void (*tests[])(void) = {TestSubscripts, TestPointers1, TestPointers2, TestPointers3, TestPointers4};
#define NUM (sizeof(tests) / sizeof(*tests))
clock_t start[NUM + 1] = {0};
clock_t end[NUM + 1] = {0};
clock_t total[NUM + 1] = {0};
int i, j;
int iterations = 10;
/* don't count the first iteration, let the cache stabilize */
for (i = 0; i <= iterations; i++)
{
for (j = 0; j < NUM; j++)
{
start[j] = clock();
tests[j]();
end[j] = clock();
if (i) /* skip first one */
total[j] += end[j] - start[j];
}
if (i) /* skip first */
{
printf("%2i: ", i);
for (j = 0 ; j < NUM; j++)
printf("test%i = %3li ", j + 1, end[j] - start[j]);
printf("\n");
}
}
printf("\nAve: ");
for (j = 0; j < NUM; j++)
printf("test%i = %3li ", j + 1, total[j] / iterations);
printf("\n");
}
Same driver using a pointer to the array of function pointers:
The loops to test:
void TestTimings(void)
{
void (*tests[])(void) = {TestSubscripts, TestPointers1, TestPointers2, TestPointers3, TestPointers4};
void (**pf)(void);
#define NUM (sizeof(tests) / sizeof(*tests))
clock_t start[NUM + 1] = {0};
clock_t end[NUM + 1] = {0};
clock_t total[NUM + 1] = {0};
int i, j;
int iterations = 10;
/* don't count the first iteration, let the cache stabilize */
for (i = 0; i <= iterations; i++)
{
pf = tests;
for (j = 0; j < NUM; j++)
{
start[j] = clock();
(*pf++)();
end[j] = clock();
if (i) /* skip first one */
total[j] += end[j] - start[j];
}
if (i) /* skip first */
{
printf("%2i: ", i);
for (j = 0 ; j < NUM; j++)
printf("test%i = %3li ", j + 1, end[j] - start[j]);
printf("\n");
}
}
printf("\nAve: ");
for (j = 0; j < NUM; j++)
printf("test%i = %3li ", j + 1, total[j] / iterations);
printf("\n");
}