正如@user3528438提到的那样,您可以查看汇编输出。考虑以下示例:
inline int sub2ind(const int sub_height, const int sub_width, const int width) {
return sub_height * width + sub_width;
}
int main() {
volatile int n[] = {1, 2, 3};
return sub2ind(n[0], n[1], n[2]);
}
如果没有进行优化编译 (g++ -S test.cc
),则得到的代码中sub2ind
没有被嵌入:
main:
.LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $32, %rsp
movl $1, -16(%rbp)
movl $2, -12(%rbp)
movl $3, -8(%rbp)
movq -16(%rbp), %rax
movq %rax, -32(%rbp)
movl -8(%rbp), %eax
movl %eax, -24(%rbp)
movl -24(%rbp), %edx
movl -28(%rbp), %ecx
movl -32(%rbp), %eax
movl %ecx, %esi
movl %eax, %edi
call _Z7sub2indiii
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
使用优化编译(g++ -S -O3 test.cc
)会导致sub2ind
被内联,大部分被优化掉:
main:
.LFB1:
.cfi_startproc
movl $1, -24(%rsp)
movl $2, -20(%rsp)
movq -24(%rsp), %rax
movl $3, -16(%rsp)
movq %rax, -40(%rsp)
movl $3, -32(%rsp)
movl -32(%rsp), %eax
movl -36(%rsp), %edx
movl -40(%rsp), %ecx
imull %ecx, %eax
addl %edx, %eax
ret
.cfi_endproc
如果您确信函数未被内联,请先确保在编译器选项中启用了优化。