Tob*_*oby 3 c optimization if-statement
(C)如果我有一个包含if的函数,如果条件为真,则可以返回某个值,然后返回另一个值.是否或多或少有效使用别人或不打扰?
即......
int foo (int a) {
if ((a > 0) && (a < SOME_LIMIT)) {
b = a //maybe b is some global or something
return 0;
} else {
return 1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要不就
int foo (int a) {
if ((a > 0) && (a < SOME_LIMIT)) {
b = a //maybe b is some global or something
return 0;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
假设GCC,编译代码中的第一个实现结果是否与第二个不同?
我需要在这里尽可能高效,因此可能减少其他分支将是很好的 - 但风格上我的内部强迫症不喜欢看到一个不为0或无效的返回作为函数中的最后一条指令作为其不太清楚发生了什么.所以,如果它无论如何都会被淘汰,那么我可以把别的东西留在那里......
您可以使用-O3 -S
选项运行gcc 以生成优化的汇编代码,以便您可以查看(和比较)优化的汇编.我对您的源进行了以下更改以使它们编译.
文件ac:
int b;
int foo (int a) {
if ((a > 0) && (a < 5000)) {
b = a;
return 0;
} else {
return 1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
文件bc:
int b;
int foo (int a) {
if ((a > 0) && (a < 5000)) {
b = a;
return 0;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
当编译交流与gcc -O3 -S a.c
文件的创建.在我的机器上它看起来像这样:
.file "a.c"
.text
.p2align 4,,15
.globl foo
.type foo, @function
foo:
.LFB0:
.cfi_startproc
movl 4(%esp), %edx
movl $1, %eax
leal -1(%edx), %ecx
cmpl $4998, %ecx
ja .L2
movl %edx, b
xorb %al, %al
.L2:
rep
ret
.cfi_endproc
.LFE0:
.size foo, .-foo
.comm b,4,4
.ident "GCC: (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1"
.section .note.GNU-stack,"",@progbits
Run Code Online (Sandbox Code Playgroud)
使用文件bs编译bc时会创建.在我的机器上它看起来像这样:gcc -O3 -S b.c
.file "b.c"
.text
.p2align 4,,15
.globl foo
.type foo, @function
foo:
.LFB0:
.cfi_startproc
movl 4(%esp), %edx
movl $1, %eax
leal -1(%edx), %ecx
cmpl $4998, %ecx
ja .L2
movl %edx, b
xorb %al, %al
.L2:
rep
ret
.cfi_endproc
.LFE0:
.size foo, .-foo
.comm b,4,4
.ident "GCC: (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1"
.section .note.GNU-stack,"",@progbits
Run Code Online (Sandbox Code Playgroud)
请注意,组装的实现foo:
是相同的.因此,在这种情况下,使用此版本的GCC,编写代码的方式无关紧要.
归档时间: |
|
查看次数: |
5456 次 |
最近记录: |