一天一个CRT函数 memset

memset是我们coding的时候经常用到的内存操作函数,就是用来初始化结构体的数据。不过我还是推荐在C++中用构造函数的初始化列表来初始化,但对付C方式的struct还是memset吧,M$把这个CRT API实现得非常非常高效!

7.memset

   1: /***
   2: *Purpose:
   3: *       把buffer所指内存区域的前uLen个字节设置成字符cVal
   4: *
   5: *Entry:
   6: *       T *pDest - pointer to memory to fill with val
   7: *       C val   - value to put in dst bytes
   8: *       unsigned int uLen - number of bytes of dst to fill
   9: *
  10: *Exit:
  11: *       returns pDest, with filled bytes
  12: *
  13: *Exceptions:
  14: *
  15: ***/
  16: template<typename T, typename C>
  17: inline T *tMemSet(T *pDest, C cVal, unsigned int uLen)
  18: {
  19:     while(uLen) 
  20:     {
  21:         *pDest++ = cVal;
  22:  
  23:         --uLen;
  24:     }
  25:  
  26:     return pDest;
  27: }

很简单明了的实现,效率当然比不上用汇编写就的。还是简单测试下吧,看看到底差多少。

测试

   1: volatile tChar buffer[] = _T("This is a test of the memset function This is a test of the memset function");
   2:  
   3: volatile const DWORD dwCount = 10000000;
   4:  
   5: DWORD dwLast = 0; 
   6: {
   7:     CCYPerformance timer(dwLast);
   8:     for(DWORD i = 0; i < dwCount; ++i)
   9:     {
  10:         CY_CRT::tMemSet(buffer, _T('*'), 40);
  11:     }
  12: }
  13: cout << dwLast << endl;
  14:  
  15: dwLast = 0; 
  16: {
  17:     CCYPerformance timer(dwLast);
  18:     for(DWORD i = 0; i < dwCount; ++i)
  19:     {
  20:         memset((void *)buffer, _T('*'), 40);
  21:     }
  22: }
  23: cout << dwLast << endl;
结果:
memset

 

 

 

 

 

呵呵,这就是差距~小样!!40多倍的差距。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值