Created
May 21, 2013 17:12
-
-
Save haberman/5621474 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Output 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++) { | |
// Switch between "cmp" and "vcmp" and measure the difference. | |
// I measure a 20% slowdown with vcmp. | |
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++) { | |
// Switch between "cmp" and "vcmp" and measure the difference. | |
// I measure a 20% slowdown with vcmp. | |
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