c++ - 如果没有 if,std::count_if 会更快吗?

标签 c++ performance gcc stl

这是 gcc std::count_if 代码

template<typename _InputIterator, typename _Predicate>
  typename iterator_traits<_InputIterator>::difference_type
  count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
 {
  [snip]
  typename iterator_traits<_InputIterator>::difference_type __n = 0;
  for (; __first != __last; ++__first)
    if (__pred(*__first))
      ++__n;
  return __n;
}

我的问题:使用它会更好(即更快)吗

__n += __pred(*__first); // instead of the if statement

这个版本总是做一个添加,但不做一个分支。

最佳答案

你给的替换是等价的,因为谓词的限制比你想象的要少得多:

  • 任何可以在条件上下文中使用的东西(可以根据上下文转换为 bool),是谓词的有效返回类型(显式转换为 bool 就够了)。
  • 该返回类型对添加到迭代器差异类型的 react 很有趣。

25 Algorithms library [algorithms]

25.1 General [algorithms.general]

8 The Predicate parameter is used whenever an algorithm expects a function object (20.9) that, when applied to the result of dereferencing the corresponding iterator, returns a value testable as true. In other words, if an algorithm takes Predicate pred as its argument and first as its iterator argument, it should work correctly in the construct pred(*first) contextually converted to bool (Clause 4). The function object pred shall not apply any non-constant function through the dereferenced iterator.

最有可能给你的替代消化不良的返回是一个标准的整数类型,一个既不是 0 也不是 1 的值。

另外,请记住,如今编译器实际上可以非常好地进行优化(尤其是 C++ 编译器需要这样做,所有这些模板内容都分层得很深)。

关于c++ - 如果没有 if,std::count_if 会更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245969/

相关文章:

c++ - std::atomic <>后递增何时发生?

c++ - 旋转矩阵 n 次

ruby-on-rails - 如何在 Ruby on Rails 中启用压缩?

c - gcc __attribute__ 放置之间的差异

c - GCC - memcpy 自动复制空字符?

c++ - boost 错误信息

c++ - 调用 operator== 时,MSVC 不会执行用户定义的到 std::nullptr_t 的隐式转换

performance - azure托管的mac管道,关于如何使其更快的建议,目前非常慢,在桌面上5分钟,在服务器上接近20

programming-languages - 我应该使用什么语言和(可能的)Web应用程序框架来开发高流量Web应用程序?

c - GCC:为什么这个 fprintf 有一个 -Wformat 警告?