设为首页 加入收藏

TOP

写高并发程序时慎用strncpy和sprintf(四)
2019-01-05 20:09:04 】 浏览:506
Tags:并发 程序 慎用 strncpy sprintf
s
/= 400; //20万 WriteLog(LOG_KEY, "BaseTest %lu", nTimes); PerformanceTestLog(TEST_LOG_INF, "WriteLog 1"); for (i = 0; i < nTimes; ++i) { WriteLog(LOG_ERROR, "this is loging"); } PerformanceTestLog(TEST_LOG_INF, "WriteLog 2"); for (i = 0; i < nTimes; ++i) { WriteLog(LOG_ERROR, "this is loging this is loging this is loging"); } PerformanceTestLog(TEST_LOG_INF, "WriteLog 3"); for (i = 0; i < nTimes; ++i) { WriteLog(LOG_ERROR, "this is loging this is loging this is loging this is loging this is loging this is loging"); } stopTimer(TEST_LOG_INF, 0); return 0; }

 

 

         从基准测试结果可以知道,sprintf系列函数效率是比较低的,是我们常见的字符串操作函数的1/10以下。

         我个人的解决方案是sprintf该用还是用,但有些情况不是特别必要用的情况,用自己写一些小函数代替。例如下面这个宏是用来代替sprintf(buf, "%02d", i)的

 

//sprintf比较慢 这里需要写一些简单的字符串组装函数
//这个是代替%02d的(但不会添加\0结尾)顾名思义,传入的值需要保证0 <= vallue < 100
//再次提醒注意,这里为了方便调用,不会添加\0! 不会添加\0! 不会添加\0!
#define itoaLt100Ge0(value, buff_output) do \
{\
    int value_ = (int)(value);\
    char *buff_output_ = (buff_output);\
    if ((value_) >= 10) { int nDigit_ = value_ / 10; buff_output_[0] = '0' + nDigit_; buff_output_[1] = '0' + (value_ - nDigit_ * 10); }\
    else { buff_output_[0] = '0'; buff_output_[1] = '0' + (value_);  } \
} while (0)
 

 

        

         总结一下就是:高并发交易需要慎用strncpy和sprintf,因为不恰当使用它们可能会成为程序性能瓶颈。

         如果大家有啥想法,欢迎分享,我是黄词辉,一个程序员 ^_^

 

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇cf121C. Lucky Permutation(康托.. 下一篇洛谷P2973 [USACO10HOL]赶小猪(高..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目