C++ 将字符串转换为 int 的最有效方法(比 atoi 更快)

2022-01-12 00:00:00 string performance int type-conversion c++

正如标题中提到的,我正在寻找比 atoi 更能提供性能的东西.目前,我知道最快的方法是

As mentioned in the title, I'm looking for something that can give me more performance than atoi. Presently, the fastest way I know is

atoi(mystring.c_str())

最后,我更喜欢不依赖 Boost 的解决方案.有没有人有很好的性能技巧来做到这一点?

Finally, I would prefer a solution that doesn't rely on Boost. Does anybody have good performance tricks for doing this?

附加信息:int不会超过20亿,总是正数,字符串中没有小数位.

Additional Information: int will not exceed 2 billion, it is always positive, the string has no decimal places in it.

推荐答案

我尝试了使用查找表的解决方案,但发现它们充满了问题,而且实际上速度不是很快.结果证明,最快的解决方案是最没有想象力的:

I experimented with solutions using lookup tables, but found them fraught with issues, and actually not very fast. The fastest solution turned out to be the least imaginitive:

int fast_atoi( const char * str )
{
    int val = 0;
    while( *str ) {
        val = val*10 + (*str++ - '0');
    }
    return val;
}

使用一百万个随机生成的字符串运行基准测试:

Running a benchmark with a million randomly generated strings:

fast_atoi : 0.0097 seconds
atoi      : 0.0414 seconds

公平地说,我还通过强制编译器不要内联它来测试这个函数.结果还是不错的:

To be fair, I also tested this function by forcing the compiler not to inline it. The results were still good:

fast_atoi : 0.0104 seconds
atoi      : 0.0426 seconds

只要你的数据符合 fast_atoi 函数的要求,这是相当合理的性能.要求是:

Provided your data conforms to the requirements of the fast_atoi function, that is pretty reasonable performance. The requirements are:

  1. 输入字符串只包含数字字符,或者为空
  2. 输入字符串代表一个从 0 到 INT_MAX
  3. 的数字

相关文章