c++ - 为什么 '==' 在 std::string 上很慢?

标签 c++ string compare std

在分析我的应用程序时,我意识到很多时间都花在了字符串比较上。所以我写了一个简单的基准测试,我很惊讶 '==' 比 string::compare 和 strcmp 慢得多!这是代码,谁能解释这是为什么?或者我的代码有什么问题?因为根据标准 '==' 只是一个运算符重载,只是返回 !lhs.compare(rhs)。

#include <iostream>
#include <vector>
#include <string>
#include <stdint.h>
#include "Timer.h"
#include <random>
#include <time.h>
#include <string.h>
using namespace std;
uint64_t itr  = 10000000000;//10 Billion
int len = 100;
int main() {
  srand(time(0));
  string s1(len,random()%128);
  string s2(len,random()%128);

uint64_t a = 0;
  Timer t;
  t.begin();
  for(uint64_t i =0;i<itr;i++){
    if(s1 == s2)
      a = i;
  }
  t.end();

  cout<<"==       took:"<<t.elapsedMillis()<<endl;

  t.begin();
  for(uint64_t i =0;i<itr;i++){
    if(s1.compare(s2)==0)
      a = i;
  }
  t.end();

  cout<<".compare took:"<<t.elapsedMillis()<<endl;

  t.begin();
  for(uint64_t i =0;i<itr;i++){
    if(strcmp(s1.c_str(),s2.c_str()))
      a = i;
  }
  t.end();

  cout<<"strcmp   took:"<<t.elapsedMillis()<<endl;

  return a;
}

结果如下:

==       took:5986.74
.compare took:0.000349
strcmp   took:0.000778

还有我的编译标志:

CXXFLAGS = -O3 -Wall -fmessage-length=0 -std=c++1y

我在 x86_64 linux 机器上使用 gcc 4.9。

显然使用 -o3 做了一些优化,我猜这会完全推出最后两个循环;但是,使用 -o2 的结果仍然很奇怪:

10 亿次迭代:

==       took:19591
.compare took:8318.01
strcmp   took:6480.35

附: Timer 只是一个用于测量花费时间的包装类;我对此非常肯定:D

Timer 类的代码:

#include <chrono>

#ifndef SRC_TIMER_H_
#define SRC_TIMER_H_


class Timer {
  std::chrono::steady_clock::time_point start;
  std::chrono::steady_clock::time_point stop;
public:
  Timer(){
    start = std::chrono::steady_clock::now();
    stop = std::chrono::steady_clock::now();
  }
  virtual ~Timer() {}

  inline void begin() {
    start = std::chrono::steady_clock::now();
  }

  inline void end() {
    stop = std::chrono::steady_clock::now();
  }

  inline double elapsedMillis() {
    auto diff = stop - start;
    return  std::chrono::duration<double, std::milli> (diff).count();
  }

  inline double elapsedMicro() {
    auto diff = stop - start;
    return  std::chrono::duration<double, std::micro> (diff).count();
  }

  inline double elapsedNano() {
    auto diff = stop - start;
    return  std::chrono::duration<double, std::nano> (diff).count();
  }

  inline double elapsedSec() {
    auto diff = stop - start;
    return std::chrono::duration<double> (diff).count();
  }
};

#endif /* SRC_TIMER_H_ */

最佳答案

更新:http://ideone.com/rGc36a 的改进基准输出

==       took:21
.compare took:21
strcmp   took:14
==       took:21
.compare took:25
strcmp   took:14

事实证明,让它有意义地工作的关键是“智取”编译器在编译时预测正在比较的字符串的能力:

// more strings that might be used...
string s[] = { {len,argc+'A'}, {len,argc+'A'}, {len, argc+'B'}, {len, argc+'B'} };

if(s[i&3].compare(s[(i+1)&3])==0)  // trickier to optimise
  a += i;  // cumulative observable side effects

请注意,当文本可能嵌入 NUL 时,strcmp 在功能上并不等同于 ==.compare,因为前者将得到“提前退出”。 (这不是上面“更快”的原因,但请阅读下面的评论以了解字符串长度/内容等可能的变化。)


讨论/较早的答案

看看你的实现——例如

echo '#include <string>' > stringE.cc
g++ -E stringE.cc | less

搜索 basic_string 模板,然后搜索 operator== 处理两个字符串实例 - 我的是:

template<class _Elem,
    class _Traits,
    class _Alloc> inline
    bool __cdecl operator==(
            const basic_string<_Elem, _Traits, _Alloc>& _Left,
            const basic_string<_Elem, _Traits, _Alloc>& _Right)
    {
    return (_Left.compare(_Right) == 0);
    }

请注意,operator== 是内联的,只需调用 compare不可能在启用正常优化级别的情况下始终会明显变慢,尽管优化器可能偶尔会由于微妙的原因而更好地优化一个循环周围代码的副作用。

您的表面问题可能是由例如您的代码被优化到超出预期的工作点,for 循环任意展开到不同程度,或者优化或您的时间安排中的其他怪癖或错误。当您有不变的输入和没有任何累积副作用的循环时,这并不罕见(即编译器可以计算出不使用 a 的中间值,因此只有最后一个 a = i 需要生效)。

所以,学习编写更好的基准测试。在这种情况下,这有点棘手,因为在内存中有许多不同的字符串准备好调用比较,并以优化器在编译时无法预测的方式选择它们,但速度仍然足够快,不会压倒和掩盖影响的字符串比较代码,不是一件容易的事。此外,超出一点 - 比较分布在更多内存中的事物会使缓存影响与基准测试更相关,这进一步模糊了真正的比较性能。

不过,如果我是你,我会从文件中读取一些字符串 - 将每个字符串推送到 vector,然后遍历 vector 进行三个比较中的每一个相邻元素之间的操作。然后编译器不可能预测结果中的任何模式。您可能会发现 compare/==strcmp 更快/更慢,因为字符串的第一个或三个字符通常不同,但反之亦然在结尾处相等或仅不同的长字符串,因此请确保在得出您了解性能概况之前尝试不同类型的输入。

关于c++ - 为什么 '==' 在 std::string 上很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28734684/

相关文章:

c++ - Microsoft Cryptographic API 是否允许从字节流创建 ECDSA key ?

c++ - 调用了错误的 operator() 重载

c++ - eclipse cdt - 如何在 C/C++ 编辑器窗口中设置工具提示窗口的背景颜色?

android - 比较android中的两个Arraylists

arrays - 比较两个文本框中的单词以找出差异?

django - 比较 django TestCase 中的查询集

c++ - 将 CRTP 与 SFINAE 混合

string - Lua:在分隔字符串中查找标记

python - 用户输入困难并替换字母

android - 如何清除蓝牙输入流缓冲区