Created
May 17, 2013 15:27
-
-
Save anonymous/5599803 to your computer and use it in GitHub Desktop.
Simple benchmark to measure the cost of virtual functions.
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
#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 icmp(const void *a, const void *b) { return cmp(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), vcmp); | |
} | |
} | |
// Note that cmp and icmp are identical below because cmp is inlined into | |
// icmp. | |
// | |
// $ g++ -O3 -o test.o -c test.cc | |
// $ objdump --demangle -d -r -M intel test.o | |
// | |
// test.o: file format elf64-x86-64 | |
// | |
// | |
// Disassembly of section .text: | |
// | |
// 0000000000000000 <vcmp(void const*, void const*)>: | |
// 0: 48 89 f9 mov rcx,rdi | |
// 3: 48 8b 3d 00 00 00 00 mov rdi,QWORD PTR [rip+0x0] # a <vcmp(void const*, void const*)+0xa> | |
// 6: R_X86_64_PC32 c-0x4 | |
// a: 48 89 f2 mov rdx,rsi | |
// d: 48 89 ce mov rsi,rcx | |
// 10: 48 8b 07 mov rax,QWORD PTR [rdi] | |
// 13: 48 8b 00 mov rax,QWORD PTR [rax] | |
// 16: ff e0 jmp rax | |
// 18: 0f 1f 84 00 00 00 00 nop DWORD PTR [rax+rax*1+0x0] | |
// 1f: 00- | |
// | |
// 0000000000000020 <cmp(void const*, void const*)>: | |
// 20: 8b 06 mov eax,DWORD PTR [rsi] | |
// 22: 2b 07 sub eax,DWORD PTR [rdi] | |
// 24: c3 ret | |
// 25: 66 66 2e 0f 1f 84 00 data32 nop WORD PTR cs:[rax+rax*1+0x0] | |
// 2c: 00 00 00 00- | |
// | |
// 0000000000000030 <icmp(void const*, void const*)>: | |
// 30: 8b 06 mov eax,DWORD PTR [rsi] | |
// 32: 2b 07 sub eax,DWORD PTR [rdi] | |
// 34: c3 ret | |
// | |
// Disassembly of section .text._ZN7Compare7compareEPKvS1_: | |
// | |
// 0000000000000000 <Compare::compare(void const*, void const*)>: | |
// 0: 8b 02 mov eax,DWORD PTR [rdx] | |
// 2: 2b 06 sub eax,DWORD PTR [rsi] | |
// 4: c3 ret | |
// | |
// [...] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment