Skip to content

Instantly share code, notes, and snippets.

@haberman
Created May 21, 2013 17:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haberman/5621682 to your computer and use it in GitHub Desktop.
Save haberman/5621682 to your computer and use it in GitHub Desktop.
// On my system:
// virtual call time: 4.340
// non-virtual call time: 3.970
// virtual call overhead 9.32%
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#define NOINLINE __attribute__ ((noinline))
#define N 1000000
#define M 100
class Compare {
public:
virtual int vcompare(const void *a, const void *b) {
return *(int*)b - *(int*)a;
}
int compare(const void *a, const void *b) NOINLINE {
return *(int*)b - *(int*)a;
}
};
Compare* c;
int vcmp(const void *a, const void *b) { return c->vcompare(a, b); }
int icmp(const void *a, const void *b) { return c->compare(a, b); }
int main() {
int *array = new int[N];
c = new Compare();
double vsec, isec;
clock_t before = clock();
for (int i = 0; i < M; i++) { qsort(array, N, sizeof(int), vcmp); }
vsec = (double)(clock() - before) / CLOCKS_PER_SEC;
printf("virtual call time: %0.3f\n", vsec);
before = clock();
for (int i = 0; i < M; i++) { qsort(array, N, sizeof(int), icmp); }
isec = (double)(clock() - before) / CLOCKS_PER_SEC;
printf("non-virtual call time: %0.3f\n", isec);
printf("virtual call overhead %0.2f%%\n", (vsec - isec) * 100 / isec);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment