一天一个CRT函数 memcmp

今天接着Buffer Manipulation函数的介绍,刚开始的几个函数算法都相当简单,没有什么可比性。权当练习打字吧~咳咳~

3.memcmp/wmemcmp

实现

/****
Purpose:
比较内存区域buf1和buf2的前uCnt个字节

Entry:
T *buf1 - buffer1
T *buf2 - buffer2
unsigned cnt - max number of bytes to search

Exit:
< 0 buf1 小于 buf2
= 0 buf1 等于 buf2
> 0 buf1 大于 buf2

Uses:

Exceptions:

***/
template<typename T>
inline int tMemCmp(T *pBuf1, T *pBuf2, unsigned int uCnt)
{
while( uCnt )
{
if( *pBuf1++ != *pBuf2++ )
// pBuf1[-1]、pBuf2[-1]是退回到不相等的字符处再进行比较
return pBuf1[-1] < pBuf2[-1] ? -1 : 1;

--uCnt;
}

return 0;
}

测试
volatile tChar first[]  = _T("123456789012345678901234567890123456789012345678901234567890");
volatile tChar second[] = _T("123456789012345678901234567890123456789012345678901234567890");

volatile int nArr1[] = {1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4};
volatile int nArr2[] = {1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 4, 1, 2, 3, 5, 3};


int result;
volatile const DWORD dwCount = 10000000;


DWORD dwLast = 0;
{
CCYPerformance timer(dwLast);
for(DWORD i = 0; i < dwCount; ++i)
{
result = memcmp((const void *)first, (const void *)second, sizeof(first) / sizeof(first[0]) );
--result;
}
}
std::cout << dwLast << std::endl;


dwLast = 0;
{
CCYPerformance timer(dwLast);
for(DWORD i = 0; i < dwCount; ++i)
{
result = CY_CRT::tMemCmp( first, second, sizeof(first) / sizeof(first[0]) );
++result;
}
}
std::cout << dwLast << std::endl;

这里提供两种测试环境(VS2008 + Release模式):
Unicode下:
Test1
Ascii下:
image

结果:

很明显,M$的汇编实现效率实在是高,Unicode下比多字节快几乎一倍(前提是自己的函数实现,而汇编则没怎么受影响!)

还是那句话:非专业人士的测试都不可靠!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值