您的位置:首页 > 其它

一天一个CRT函数 memset

2009-12-28 10:31 330 查看
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;


结果:













呵呵,这就是差距~小样!!40多倍的差距。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: