How raise to power works? Is it worth to use pow(x, 2)?

Is it more efficient to do multiplication than raise to power 2 in c++?

I am trying to do final detailed optimizations. Will the compiler treat x*x the same as pow(x,2)? If I remember correctly, multiplication was better for some reason, but maybe it does not matter in c++11.

Thanks


如果你将乘法与pow()标准库函数进行比较,那么是的,乘法肯定会更快。


I general, you should not worry about pico-optimizations like that unless you have evidence that there is a hot-spot (ie unless you've profiled your code under realistic scenarios and have identified a particular chunk of code. Also keep in mind that your clever tricks may actually cause performance regressions in new processors where your assumptions will no longer hold.

Algorithmic changes are where you will get the most bang for your computing buck. Focus on that.

Tinkering with multiplications and doing clever bit-hackery... eh not so much bang there* Because the current generation of optimizing compilers is really quite excellent at their job. That's not to say they can't be beat. They can, but not easily and probably only by a few people like Agner Fog.

* there are, of course, exceptions.


When it comes to performance, always make measurements to back up your assumptions. Never trust theory unless you have a benchmark that proves that theory right.

Also, keep in mind that x ^ 2 does not yield the square of 2 in C++:

#include <iostream>

int main()
{
    int x = 4;
    std::cout << (x ^ 2); // Prints 6
}

Live example.

链接地址: http://www.djcxy.com/p/15024.html

上一篇: 1,000微妙计算每微秒?

下一篇: 如何提高电力工程? 是否值得使用pow(x,2)?