我的程序在 std::pow(double,int)
函数中花费了 90% 的 CPU 时间。准确性不是这里的主要关注点,所以我想知道是否有更快的替代方案。我想尝试的一件事是强制 float ,执行操作,然后返回双倍(还没有尝试过);我担心这不是一种提高性能的可移植方式(大多数 CPU 本质上不是在 double 上运行吗?)
干杯
最佳答案
看起来 Martin Ankerl 有几篇关于此的文章,Optimized Approximative pow() in C / C++是一个,它有两个快速版本,一个如下:
inline double fastPow(double a, double b) {
union {
double d;
int x[2];
} u = { a };
u.x[1] = (int)(b * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return u.d;
}
它依赖于通过 union 进行类型双关语,这是 C++ 中未定义的行为,来自草案标准部分 9.5
[class.union]:
In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [...]
但大多数编译器包括 gcc support this with well defined behavior :
The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type
但这并不像 this article points out 那样通用和我一样point out in my answer here使用 memcpy
应该生成相同的代码并且不会调用未定义的行为。
他还链接到第二个 Optimized pow() approximation for Java, C / C++, and C# .
第一篇文章还链接到他的微基准 here
关于c++ - 什么比 std::pow 更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16782746/