所以我目前正在研究按位運算子和位操作,我遇到了兩種不同的方法來將四個 1 位元組的字組合成一個 4 位元組寬的字。
下面給出了兩種方式
找出這兩種方法后,我比較了兩者生成的反匯編代碼(使用帶有-O2標志的gcc 11編譯),我沒有反匯編及其生成的代碼的基本知識,我只知道代碼越短,函式越快(大多數時候我猜......也許有一些例外),現在對于這兩種方法,它們似乎在生成的反匯編代碼中具有相同的行數/計數,所以我猜他們有相同的表現?
我也對指令的順序感到好奇,第一種方法似乎交替其他指令sal>or>sal>or>sal>or,而第二種方法更統一sal>sal>sal>or>or>mov>or,這是否對性能有一些顯著影響,例如,如果我們正在處理更大的單詞?
兩種方法
int method1(unsigned char byte4, unsigned char byte3, unsigned char byte2, unsigned char byte1)
{
int combine = 0;
combine = byte4;
combine <<=8;
combine |= byte3;
combine <<=8;
combine |= byte2;
combine <<=8;
combine |= byte1;
return combine;
}
int method2(unsigned char byte4, unsigned char byte3, unsigned char byte2, unsigned char byte1)
{
int combine = 0, temp;
temp = byte4;
temp <<= 24;
combine |= temp;
temp = byte3;
temp <<= 16;
combine |= temp;
temp = byte2;
temp <<= 8;
combine |= temp;
temp = byte1;
combine |= temp;
return combine;
}
拆卸
// method1(unsigned char, unsigned char, unsigned char, unsigned char):
movzx edi, dil
movzx esi, sil
movzx edx, dl
movzx eax, cl
sal edi, 8
or esi, edi
sal esi, 8
or edx, esi
sal edx, 8
or eax, edx
ret
// method2(unsigned char, unsigned char, unsigned char, unsigned char):
movzx edx, dl
movzx ecx, cl
movzx esi, sil
sal edi, 24
sal edx, 8
sal esi, 16
or edx, ecx
or edx, esi
mov eax, edx
or eax, edi
ret
這可能是“過早優化”,但我只想知道是否有區別。
uj5u.com熱心網友回復:
我完全同意émerick Poulin 的觀點:
所以真正的答案是在你的目標機器上對其進行基準測驗,看看哪一個更快。
盡管如此,我還是創建了一個“method3()”,并使用 gcc 版本 10.3.0 反匯編了所有三個,使用 -O0 和 -O2,以下是 -O2 結果的摘要:
方法三:
int method3(unsigned char byte4, unsigned char byte3, unsigned char byte2, unsigned char byte1)
{
int combine = (byte4 << 24)|(byte3<<16)|(byte2<<8)|byte1;
return combine;
}
gcc -O2 -S:
;method1:
sall $8,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357361.html
上一篇:程式集中的間接尋址(x86)
