Skip to content

Instantly share code, notes, and snippets.

@ianliu
Last active August 29, 2015 14:02
Show Gist options
  • Save ianliu/b93fbf2bbde9380d24c5 to your computer and use it in GitHub Desktop.
Save ianliu/b93fbf2bbde9380d24c5 to your computer and use it in GitHub Desktop.
Program to compare performance of VTable versus Switch in a simple program
/* Compile with: gcc -O3 vtable-vs-switch.c -o vtable-vs-switch */
/* Execute: time ./vtable-vs-switch switch */
/* time ./vtable-vs-switch vtable */
/* Execution time should last less than a minute. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static FILE *output;
/* Define some workers with equal prototypes */
void worker1(FILE *f)
{
fprintf(f, "I'm worker 1\n");
}
void worker2(FILE *f)
{
fprintf(f, "I'm worker 2\n");
}
void worker3(FILE *f)
{
fprintf(f, "I'm worker 3\n");
}
void worker4(FILE *f)
{
fprintf(f, "I'm worker 4\n");
}
enum worker_id {
WORKER1 = 0,
WORKER2,
WORKER3,
WORKER4,
N_WORKERS,
};
/* These are for function pointer call */
typedef void (*worker)(FILE*);
worker vtable[] = {
worker1,
worker2,
worker3,
worker4,
};
void do_work_vtable(enum worker_id id)
{
(vtable[id])(output);
}
/* These are for switch style call */
void do_work_switch(enum worker_id id)
{
switch (id) {
case WORKER1: worker1(output); break;
case WORKER2: worker2(output); break;
case WORKER3: worker3(output); break;
case WORKER4: worker4(output); break;
}
}
/* Lets benchmark */
void usage(const char *prog)
{
fprintf(stderr, "Usage: %s (switch|vtable) [NUM_EXECUTIONS [OUTPUT]]\n", prog);
exit(1);
}
int main(int argc, char *argv[])
{
if (argc <= 1)
usage(argv[0]);
const char *method = argv[1];
if (strcmp(method, "switch") != 0 && strcmp(method, "vtable") != 0)
usage(argv[0]);
int N = argc >= 3 ? atoi(argv[2]) : 1000000000;
output = argc >= 4 ? fopen(argv[3], "w") : fopen("/dev/null", "w");
printf("Running experiment:\n");
printf(" Method: %s\n", method);
printf(" Number of executions: %d\n", N);
if (strcmp(method, "switch") == 0) {
while (N--)
do_work_switch(N % N_WORKERS);
} else if (strcmp(method, "vtable") == 0) {
while (N--)
do_work_vtable(N % N_WORKERS);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment