31 c optimization performance micro-optimization
在C语言中,为什么n++执行速度比n=n+1?
(int n=...; n++;)
(int n=...; n=n+1;)
Run Code Online (Sandbox Code Playgroud)
我们的老师在今天的班上问了这个问题.(这不是作业)
Bet*_*moo 102
如果你正在研究一个"石器时代"的编译器,那将是真的......
在的情况下,"石器时代":
++n快于n++快于n=n+1
机床通常increment x以及add const to x
n++,您将只有2个内存访问(读取n,包含,写入n)n=n+1,您将有3个内存访问(读取n,读取const,添加n和const,写入n)但今天的编译器会自动转换n=n+1为++n,它会比你想象的更多!
同样在今天的乱序处理器虽然依然的情况下,"石器时代"反编译运行时可能不会受到影响所有在许多情况下!
bdo*_*lan 42
在GCC 4.4.3 for x86上,无论是否进行优化,它们都会编译为完全相同的汇编代码,因此需要花费相同的时间来执行.正如您在程序集中看到的那样,GCC只需转换n++为n=n+1,然后将其优化为单指令添加(在-O2中).
您的教师建议n++更快只适用于非常老的非优化编译器,这些编译器不够智能,无法选择就地更新指令n = n + 1.这些编译器已经在PC世界中淘汰多年,但仍可能出现在奇怪的专有嵌入式平台上.
C代码:
int n;
void nplusplus() {
n++;
}
void nplusone() {
n = n + 1;
}
Run Code Online (Sandbox Code Playgroud)
输出程序集(无优化):
.file "test.c"
.comm n,4,4
.text
.globl nplusplus
.type nplusplus, @function
nplusplus:
pushl %ebp
movl %esp, %ebp
movl n, %eax
addl $1, %eax
movl %eax, n
popl %ebp
ret
.size nplusplus, .-nplusplus
.globl nplusone
.type nplusone, @function
nplusone:
pushl %ebp
movl %esp, %ebp
movl n, %eax
addl $1, %eax
movl %eax, n
popl %ebp
ret
.size nplusone, .-nplusone
.ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
.section .note.GNU-stack,"",@progbits
Run Code Online (Sandbox Code Playgroud)
输出组件(带有-O2优化):
.file "test.c"
.text
.p2align 4,,15
.globl nplusplus
.type nplusplus, @function
nplusplus:
pushl %ebp
movl %esp, %ebp
addl $1, n
popl %ebp
ret
.size nplusplus, .-nplusplus
.p2align 4,,15
.globl nplusone
.type nplusone, @function
nplusone:
pushl %ebp
movl %esp, %ebp
addl $1, n
popl %ebp
ret
.size nplusone, .-nplusone
.comm n,4,4
.ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
.section .note.GNU-stack,"",@progbits
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16194 次 |
| 最近记录: |