c++ - 什么比 std::pow 更快?

标签 c++ performance

我的程序在 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/

相关文章:

c++ - 如何在 C++ 中打开特定应用程序后关闭它?

c++ - 链接问题 Boost.Python

c++ - new int[n]() 是如何工作的?

python - 当我提前知道它的长度时,我可以加快可迭代类的速度吗?

linux - 什么会导致多线程代码的运行时间发生巨大变化

ruby-on-rails - Rails 应用需要很长时间才能生成错误页面

performance - Java 是否将 new HashSet(someHashSet).contains() 优化为 O(1)?

c++ - 我应该选择什么同步方案来避免实时 C++/MFC 应用程序上的死锁?

javascript - Extjs + PHP 通过增加 Java 堆大小来增强性能

c++ - 移动而不是复制 boost::dynamic_bitset BlockInputIterator 构造函数?