今天接着Buffer Manipulation函数的介绍,刚开始的几个函数算法都相当简单,没有什么可比性。权当练习打字吧~咳咳~
实现
/****
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下:
结果:
很明显,M$的汇编实现效率实在是高,Unicode下比多字节快几乎一倍(前提是自己的函数实现,而汇编则没怎么受影响!)
还是那句话:非专业人士的测试都不可靠!