问题描述
我想知道 exp()
是否比更一般的 pow()
更快.我在 JsPerf http://jsperf.com/pow-vs-exp 上运行了快速基准测试,它向我展示了有趣的结果.
I was wondering if exp()
is faster than more general pow()
. I run fast benchmark on JsPerf http://jsperf.com/pow-vs-exp and it shown interesting results for me.
Math.exp(logBase * exponent); // fastest
Math.exp(Math.log(base) * exponent); // middle
Math.pow(base, exponent); // slowest
我知道结果会因架构和语言而有很大差异,但我也对理论观点感兴趣.pow(a, b)
是实现为 exp(log(a) * b)
还是有一些更聪明的方法如何直接"协同计算能力(在 C++ 中,C# 或 JavaScript).某些架构上是否有针对 exp、log 或 pow 的 CPU 指令?
I know that results will heavily vary on architecture and language but I am also interested in theoretical point of view. Is pow(a, b)
implemented as exp(log(a) * b)
or is there some more clever way how co compute power "directly" (in C++, C# or JavaScript). Are there CPU instructions for exp, log or pow on some architectures?
据我所知,exp()
和 log()
都是使用一些泰勒级数计算的,计算起来非常昂贵.这让我相信,对于恒定的力量基础,这段代码
As far as I know, both exp()
and log()
are computed using some Taylor series and are pretty expensive to compute. This makes me believe that for constant base of power, this code
double logBase = log(123.456);
for (int i = 0; i < 1024; ++i) {
exp(logBase * 654.321);
}
比这个好
for (int i = 0; i < 1024; ++i) {
pow(123.456, 654.321);
}
这是正确的假设吗?
推荐答案
是的,exp
通常会比 pow
更快.
Yes, exp
will be faster than pow
in general.
exp
和 log
函数将针对目标平台进行优化;可以使用许多技术,例如 Pade 逼近、线性或二值约简后逼近等.
The exp
and log
functions will be optimized for the target platform; many techniques can be used such as Pade approximation, linear or binary reduction followed by approximation, etc.
pow
函数一般会像你说的那样实现为exp(log(a) * b)
,所以明显比exp
慢代码>单独.pow
有很多特殊情况,例如负指数、整数指数、指数等于 1/2 或 1/3 等.这些会进一步减慢 pow
一般情况,因为这些测试很昂贵.
The pow
function will generally be implemented as exp(log(a) * b)
as you say, so it is obviously slower than exp
alone. There are many special cases for pow
such as negative exponents, integral exponents, exponents equal to 1/2 or 1/3, etc. These will slow down pow
even further in the general case because these tests are expensive.
请参阅关于 pow
的这个 SO 问题.
See this SO question on pow
.
这篇关于Pow() 与 exp() 性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!