Skip to content

Instantly share code, notes, and snippets.

Created May 17, 2013 08:09
Show Gist options
  • Save anonymous/5597659 to your computer and use it in GitHub Desktop.
Save anonymous/5597659 to your computer and use it in GitHub Desktop.
Simply benchmark to measure the cost of virtual functions.
#include <stdlib.h>
#define N 1000000
#define M 100
int cmp(const void *a, const void *b) { return *(int*)b - *(int*)a; }
class Compare {
public:
virtual int compare(const void *a, const void *b) { return cmp(a, b); }
};
Compare* c;
int vcmp(const void *a, const void *b) { return c->compare(a, b); }
int main() {
int *array = new int[N];
c = new Compare();
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), cmp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment