C++ most efficient way to convert string to int (faster than atoi)(C++ 将字符串转换为 int 的最有效方法(比 atoi 更快))
问题描述
正如标题中提到的,我正在寻找比 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:
- 输入字符串只包含数字字符,或者为空
- 输入字符串代表一个从 0 到
INT_MAX
的数字
这篇关于C++ 将字符串转换为 int 的最有效方法(比 atoi 更快)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 将字符串转换为 int 的最有效方法(比 atoi 更快)


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01