Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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