编译时间优化Math.pow

问题描述:

我读过,通过生成可以巧妙地使用位移和编译器生成的魔法常量的代码,可以在编译时通过已知常量优化乘法。

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.

我对以类似的hacky方式优化乘方的可能性感兴趣。我知道平方求幂,因此我想您可以大幅优化

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)

通过将预先计算的连续正方形CONSTANT嵌入到可执行文件中。我不知道这是否是一个好主意。

by embedding precomputed successive squares of CONSTANT into the executable. I'm not sure whether this is actually a good idea.

但是,当涉及到

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?

假设 pow(a,b) $ c>被实现为 exp(b * log(a))(它可能是),如果 a 是一个常数,你可以预先计算它的 log 。如果 b 是常数,它只有在它也是一个整数时才有用。

Assuming pow(a,b) is implemented as exp(b * log(a)) (which it probably is), if a is a constant then you can precompute its log. If b is a constant, it only helps if it is also an integer.