Math.pow 的编译时间优化
我读过,可以通过生成巧妙地使用位移位和编译器生成的魔术常量的代码来优化编译时已知常量的乘法。
我对以类似的黑客方式优化求幂的可能性感兴趣。我知道通过平方求幂,所以我猜你可以
pow(CONSTANT, n)
通过嵌入预先计算的 CONSTANT 的连续平方 来积极优化进入可执行文件。我不确定这是否真的是一个好主意。
但说到这里
pow(n, CONSTANT)
我就想不出什么了。有没有一种已知的方法可以有效地做到这一点? StackOverflow 的头脑对这两个问题有想法吗?
I've read that it's possible to optimize multiplication by a known constant at compile time by generating code which makes clever use of bit shifting and compiler-generated magic constants.
I'm interested in possibilities for optimizing exponentiation in a similar hacky manner. I know about exponentiation by squaring, so I guess you could aggressively optimize
pow(CONSTANT, n)
by embedding precomputed successive squares of CONSTANT into the executable. I'm not sure whether this is actually a good idea.
But when it comes to
pow(n, CONSTANT)
I can't think of anything. Is there a known way to do this efficiently? Do the minds of StackOverflow have ideas, on either problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设
pow(a,b)
实现为exp(b * log(a))
(这可能是),如果a
是一个常量,那么您可以预先计算它的log
。如果b
是一个常量,那么只有当它也是一个整数时才有用。Assuming
pow(a,b)
is implemented asexp(b * log(a))
(which it probably is), ifa
is a constant then you can precompute itslog
. Ifb
is a constant, it only helps if it is also an integer.通过平方求幂对于第二种情况是理想的,只需基本上展开循环并嵌入常数即可。当然,前提是 CONSTANT 是整数。
Exponentiation by squaring is ideal for the second case, just basically unroll the loop and embed the constants. But only if CONSTANT is an integer of course.
您可以使用加法链求幂,这是减少已知整数指数的 CPU 周期数的明智方法:https://en.wikipedia.org/wiki/Addition-chain_exponentiation
You could use addition chain exponentiation, this is a smart way to reduce the number of CPU cycles for known integer exponents : https://en.wikipedia.org/wiki/Addition-chain_exponentiation