integer string极速互转 优化过程

【前言】

在C/C++编码中有大量的string、interger互转需求,系统接口要不好用,要么性能不高。基于性能优化、个人兴趣两个主要目的,对string、integer互转优化做了大量的尝试,下面分享一下优化中的一些过程。


【优化效果概览


32位环境(-O2):

[----------] 4 tests from performance

[ RUN ] performance.int32_to_str

fi2s int32 cost: 16765 us

snprintf int32 cost: 594351 us

!!!!!!!!!!!! fi2s(32) is 35.451894 times faster than snprintf

[ OK ] performance.int32_to_str (613 ms)

[ RUN ] performance.int64_to_str

fi2s int64 cost: 189455 us

snprintf int64 cost: 1625197 us

!!!!!!!!!!!! fi2s(64) is 8.578275 times faster than snprintf

[ OK ] performance.int64_to_str (1815 ms)

[ RUN ] performance.str_to_int32

fs2i int32 cost: 3763 us

atoi int32 cost: 77420 us

!!!!!!!!!!!! fs2i(32) is 20.574010 times faster than atoi

[ OK ] performance.str_to_int32 (81 ms)

[ RUN ] performance.str_to_int64

fs2i int64 cost: 5521 us

atoi int64 cost: 168755 us

!!!!!!!!!!!! fs2i(64) is 30.566021 times faster than atoll

[ OK ] performance.str_to_int64 (174 ms)

[----------] 4 tests from performance (2683 ms total)

64位环境(-O2):

[----------] 4 tests from performance

[ RUN ] performance.int32_to_str

fi2s int32 cost: 20086 us

snprintf int32 cost: 502266 us

!!!!!!!!!!!! fi2s(32) is 25.005775 times faster than snprintf

[ OK ] performance.int32_to_str (522 ms)

[ RUN ] performance.int64_to_str

fi2s int64 cost: 80195 us

snprintf int64 cost: 1261576 us

!!!!!!!!!!!! fi2s(64) is 15.731355 times faster than snprintf

[ OK ] performance.int64_to_str (1342 ms)

[ RUN ] performance.str_to_int32

fs2i int32 cost: 4471 us

atoi int32 cost: 67413 us

!!!!!!!!!!!! fs2i(32) is 15.077835 times faster than atoi

[ OK ] performance.str_to_int32 (72 ms)

[ RUN ] performance.str_to_int64

fs2i int64 cost: 5735 us

atoi int64 cost: 115071 us

!!!!!!!!!!!! fs2i(64) is 20.064690 times faster than atoll

[ OK ] performance.str_to_int64 (121 ms)

[----------] 4 tests from performance (2057 ms total)

【整数转字符串优化】

一般用系统接口snprintf(sprintf是高危函数,不考虑)来做整数转字符串的需求,用起来稍微有点麻烦,大致如下:

char buffer[32];

snprintf(buffer, sizeof(buffer), "%d", 12345);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值