编译器是否自动优化对数学函数的重复调用? [英] Do compilers automatically optimise repeated calls to mathematical functions?
本文介绍了编译器是否自动优化对数学函数的重复调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下代码段:
#include <cmath>
// ...
float f = rand();
std::cout << sin(f) << " " << sin(f);
由于sin(f)
是定义明确的函数,因此很容易优化:
As sin(f)
is a well defined function there is an easy optimisation:
float f = rand();
float sin_f = sin(f);
std::cout << sin_f << " " << sin_f;
期望现代C ++编译器自己执行此优化是合理的吗?还是编译器无法确定sin(f)
应该始终为f
的相等值返回相同的值?
Is this an optimisation that it's reasonable to expect a modern C++ compiler to do by itself? Or is there no way for the compiler to determine that sin(f)
should always return the same value for an equal value of f
?
推荐答案
使用通过默认优化标记构建的g ++:
Using g++ built with default optimization flags:
float f = rand();
40117e: e8 75 01 00 00 call 4012f8 <_rand>
401183: 89 44 24 1c mov %eax,0x1c(%esp)
401187: db 44 24 1c fildl 0x1c(%esp)
40118b: d9 5c 24 2c fstps 0x2c(%esp)
std::cout << sin(f) << " " << sin(f);
40118f: d9 44 24 2c flds 0x2c(%esp)
401193: dd 1c 24 fstpl (%esp)
401196: e8 65 01 00 00 call 401300 <_sin> <----- 1st call
40119b: dd 5c 24 10 fstpl 0x10(%esp)
40119f: d9 44 24 2c flds 0x2c(%esp)
4011a3: dd 1c 24 fstpl (%esp)
4011a6: e8 55 01 00 00 call 401300 <_sin> <----- 2nd call
4011ab: dd 5c 24 04 fstpl 0x4(%esp)
4011af: c7 04 24 e8 60 40 00 movl $0x4060e8,(%esp)
内置-O2
:
float f = rand();
4011af: e8 24 01 00 00 call 4012d8 <_rand>
4011b4: 89 44 24 1c mov %eax,0x1c(%esp)
4011b8: db 44 24 1c fildl 0x1c(%esp)
std::cout << sin(f) << " " << sin(f);
4011bc: dd 1c 24 fstpl (%esp)
4011bf: e8 1c 01 00 00 call 4012e0 <_sin> <----- 1 call
由此我们可以看到,没有优化,编译器只使用2个调用,而只有1个带有优化,我凭经验可以说编译器确实优化了调用.
From this we can see that without optimizations the compiler uses 2 calls and just 1 with optimizations, empirically I guess, we can say the compiler does optimize the call.
这篇关于编译器是否自动优化对数学函数的重复调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文