#5
by みけCAT » 5年前
Compiler Explorerで試したところ、
if文を用いても三項演算子を用いてもcmovg命令を用いた全く同じコードに最適化される例を確認できました。
► スポイラーを表示
コンパイルしたコード
コード:
int smallest(int* arr, int size) {
int ans = arr[0];
for (int i = 1; i < size; i++) {
if (ans > arr[i]) ans = arr[i];
}
return ans;
}
int smallest2(int* arr, int size) {
int ans = arr[0];
for (int i = 1; i < size; i++) {
ans = ans > arr[i] ? arr[i] : ans;
}
return ans;
}
コンパイラ:x86-64 gcc 8.2 、-O2オプション使用)
コンパイル結果
コード:
smallest:
mov eax, DWORD PTR [rdi]
cmp esi, 1
jle .L1
lea ecx, [rsi-2]
lea rdx, [rdi+4]
lea rsi, [rdi+8+rcx*4]
.L3:
mov ecx, DWORD PTR [rdx]
cmp eax, ecx
cmovg eax, ecx
add rdx, 4
cmp rdx, rsi
jne .L3
.L1:
ret
smallest2:
mov eax, DWORD PTR [rdi]
cmp esi, 1
jle .L6
lea ecx, [rsi-2]
lea rdx, [rdi+4]
lea rsi, [rdi+8+rcx*4]
.L8:
mov ecx, DWORD PTR [rdx]
cmp eax, ecx
cmovg eax, ecx
add rdx, 4
cmp rdx, rsi
jne .L8
.L6:
ret
あまり賢くない特定のコンパイラを使わなければならない上にパフォーマンスが非常に重要である、
「間違った」方を使うとテストで不正解にされたり怒られたりする、
などの特別な事情が無いのであれば、好きな方を使えばいいでしょう。
[url=https://gcc.godbolt.org/z/z-oFtR]Compiler Explorerで試した[/url]ところ、
if文を用いても三項演算子を用いてもcmovg命令を用いた全く同じコードに最適化される例を確認できました。
[spoil]
コンパイルしたコード
[code]
int smallest(int* arr, int size) {
int ans = arr[0];
for (int i = 1; i < size; i++) {
if (ans > arr[i]) ans = arr[i];
}
return ans;
}
int smallest2(int* arr, int size) {
int ans = arr[0];
for (int i = 1; i < size; i++) {
ans = ans > arr[i] ? arr[i] : ans;
}
return ans;
}
[/code]
コンパイラ:x86-64 gcc 8.2 、-O2オプション使用)
コンパイル結果
[code]
smallest:
mov eax, DWORD PTR [rdi]
cmp esi, 1
jle .L1
lea ecx, [rsi-2]
lea rdx, [rdi+4]
lea rsi, [rdi+8+rcx*4]
.L3:
mov ecx, DWORD PTR [rdx]
cmp eax, ecx
cmovg eax, ecx
add rdx, 4
cmp rdx, rsi
jne .L3
.L1:
ret
smallest2:
mov eax, DWORD PTR [rdi]
cmp esi, 1
jle .L6
lea ecx, [rsi-2]
lea rdx, [rdi+4]
lea rsi, [rdi+8+rcx*4]
.L8:
mov ecx, DWORD PTR [rdx]
cmp eax, ecx
cmovg eax, ecx
add rdx, 4
cmp rdx, rsi
jne .L8
.L6:
ret
[/code]
[/spoil]
あまり賢くない特定のコンパイラを使わなければならない上にパフォーマンスが非常に重要である、
「間違った」方を使うとテストで不正解にされたり怒られたりする、
などの特別な事情が無いのであれば、好きな方を使えばいいでしょう。