samedi 19 mars 2011

Les optimisations arithmétiques

À la question, lesquelles de ces fonctions sont optimisées par le compilateur ?

#define SIZE 16
int const Size = SIZE;

int withMacro(int x)
{
return x * SIZE;
}

int withConstant(int x)
{
return x * Size;
}

int withDecal(int x)
{
return x << 4;
}

int withMacro3(int x)
{
return x * SIZE * SIZE * SIZE;
}

int withConstant3(int x)
{
return x * Size * Size * Size;
}

int withDecal3(int x)
{
return x << 12;
}



La réponse est: Toutes ! En fait, les trois premières et les trois dernières produisent respectivement exactement le meme code un fois dessasemblées:

(gdb) disassemble withMacro(int)
Dump of assembler code for function _Z9withMacroi:
0x00000000 <+0>: push %ebp
0x00000001 <+1>: mov %esp,%ebp
0x00000003 <+3>: mov 0x8(%ebp),%eax
0x00000006 <+6>: pop %ebp
0x00000007 <+7>: shl $0x4,%eax
0x0000000a <+10>: ret
End of assembler dump.
(gdb) disassemble withConstant(int)
Dump of assembler code for function _Z12withConstanti:
0x00000010 <+0>: push %ebp
0x00000011 <+1>: mov %esp,%ebp
0x00000013 <+3>: mov 0x8(%ebp),%eax
0x00000016 <+6>: pop %ebp
0x00000017 <+7>: shl $0x4,%eax
0x0000001a <+10>: ret
End of assembler dump.
(gdb) disassemble withDecal(int)
Dump of assembler code for function _Z9withDecali:
0x00000020 <+0>: push %ebp
0x00000021 <+1>: mov %esp,%ebp
0x00000023 <+3>: mov 0x8(%ebp),%eax
0x00000026 <+6>: pop %ebp
0x00000027 <+7>: shl $0x4,%eax
0x0000002a <+10>: ret
End of assembler dump.
(gdb) quit

Et pout les versions 'au cube':

(gdb) disassemble withMacro3
Dump of assembler code for function _Z10withMacro3i:
0x00000030 <+0>: push %ebp
0x00000031 <+1>: mov %esp,%ebp
0x00000033 <+3>: mov 0x8(%ebp),%eax
0x00000036 <+6>: pop %ebp
0x00000037 <+7>: shl $0xc,%eax
0x0000003a <+10>: ret
End of assembler dump.
(gdb) disassemble withConstant3
Dump of assembler code for function _Z13withConstant3i:
0x00000040 <+0>: push %ebp
0x00000041 <+1>: mov %esp,%ebp
0x00000043 <+3>: mov 0x8(%ebp),%eax
0x00000046 <+6>: pop %ebp
0x00000047 <+7>: shl $0xc,%eax
0x0000004a <+10>: ret
End of assembler dump.
(gdb) disassemble withDecal3
Dump of assembler code for function _Z10withDecal3i:
0x00000050 <+0>: push %ebp
0x00000051 <+1>: mov %esp,%ebp
0x00000053 <+3>: mov 0x8(%ebp),%eax
0x00000056 <+6>: pop %ebp
0x00000057 <+7>: shl $0xc,%eax
0x0000005a <+10>: ret
End of assembler dump.
(gdb) quit

0 commentaires:

Enregistrer un commentaire