#include <iostream>
#include <string.h>
#include <Windows.h>
#include <strsafe.h>
#include <assert.h>
char* CustomStrCpy( char* Dest, const size_t CbDest, const char* Src )
{
if( NULL == Dest || 0 == CbDest || NULL == Src )
{
assert( false );
return NULL;
}
const size_t CbSrc = strlen( Src ) + 1;
if( CbDest >= CbSrc )
{
memcpy( Dest, Src, CbSrc );
}
else
{
memcpy( Dest, Src, CbDest - 1 );
Dest[ CbDest - 1 ] = '\0';
}
return Dest;
}
int main()
{
//操作的字符串
char Dest[ 128 ];//Dest的空间一定要能够储存Src,不然strcpy没检查大小会非法操作,这就是为什么strcpy不安全的原因
const char* Src = "123456789123456789123456789123456789123456789123456789";
//测试次数
const int TestSumCount = 10;
//当前测试数
int TestCount = 0;
//测试函数个数
const int TestMethodCount = 3;
//每个函数测试总共话费时间
DWORD CostTime[ TestMethodCount ] = { 0 };
//单次花费时间
DWORD TempCostTime = 0;
//函数名称
const char* TestMethod[ TestMethodCount ] = { "StringCbCopy", "CustomStrCpy", "strcpy" };
//循环测试
while( TestCount < TestSumCount )
{
std::cout<<"Test of "<<TestCount + 1<<" times."<<std::endl;
//
DWORD BeginTick = GetTickCount();
//循环500万次拷贝字符
for( int i = 0; i < 5000000; ++i )
{
//微软提供非标准的字符串安全拷贝函数
StringCbCopy( Dest, sizeof( Dest ), Src );
}
TempCostTime = GetTickCount() - BeginTick;
std::cout<<TestMethod[ 0 ]<<" cost: "<<TempCostTime<<std::endl;
CostTime[ 0 ] += TempCostTime;
//
BeginTick = GetTickCount();
for( int i = 0; i < 5000000; ++i )
{
//我们自己写的模拟字符安全拷贝函数
CustomStrCpy( Dest, sizeof( Dest ), Src );
}
TempCostTime = GetTickCount() - BeginTick;
std::cout<<TestMethod[ 1 ]<<" cost: "<<TempCostTime<<std::endl;
CostTime[ 1 ] += TempCostTime;
//
BeginTick = GetTickCount();
for( int i = 0; i < 5000000; ++i )
{
//CRL字符串拷贝函数
strcpy( Dest, Src );
}
TempCostTime = GetTickCount() - BeginTick;
std::cout<<TestMethod[ 2 ]<<" cost: "<<TempCostTime<<std::endl;
CostTime[ 2 ] += TempCostTime;
std::cout<<"------------"<<std::endl;
++TestCount;
//休息一下进行下一次测试
Sleep( 1000 );
}
std::cout<<std::endl;
std::cout<<"Avg cost time:"<<std::endl;
//花费最少时间
DWORD MinCostTime = -1;
//花费最少时间的函数
const char* MinCostTimeMethod = NULL;
//平均时间
for( int i = 0; i < TestMethodCount; ++i )
{
std::cout<<TestMethod[ i ]<<" avg cost:"<<CostTime[ i ] / TestSumCount <<std::endl;
if( CostTime[ i ] < MinCostTime )
{
MinCostTime = CostTime[ i ];
MinCostTimeMethod = TestMethod[ i ];
}
}
std::cout<<std::endl;
std::cout<<"Avg performance:"<<std::endl;
//性能比对
for( int i = 0; i < TestMethodCount; ++i )
{
std::cout<<TestMethod[ i ]<<" performance:"<<( float )MinCostTime / CostTime[ i ] * 100.0f<<"%"<<" of "<<MinCostTimeMethod<<std::endl;
}
//测试结果strcpy性能最好我机器上基本是StringCbCopy10倍性能
//StringCbCopy性能最差比我们自定义的拷贝函数还慢大概4倍(机器不一样可能结果有变化)
//这样的结果基本上可以肯定strsafe.h安全库里面的函数性能都比较慢
//因为是安全类型所以要做很多验证操作这个也是必须的安全保障,但是效率还是比想象当中的低
return 0;
}
结果如下
字符串拷贝StringCbCopy函数和自定义CustomStrCpy函数和strcpy函数的性能对比
最新推荐文章于 2022-09-30 00:28:53 发布