xx服务中需要对IP包进行简单的加解密,
以前有段时间也是用过简单加解密,
通过测试发现占用了大量的时间, 如果能够提高其执行效率,那么对提升xx服务性能将有很好的帮助
oprfile测试结果:
CPU: CPU with RTC device, speed 2800.22 MHz (estimated)
Counted RTC_INTERRUPTS events (RTC interrupts/sec (rounded up to power of two)) count 1024
vma samples % app name symbol name
c01070c0 73441111 83.6575 vmlinux default_idle
c0121690 1086084 1.2372 vmlinux do_softirq
c0141d80 1078445 1.2285 vmlinux fget
08053abe 635922 0.7244 iptun crypt //加解密函数, 非常占cpu
原来算法:
void crypt(unsigned char *data, int length )
{
for( int i = 0; i < length; i++ )
{
data[i] ^= '@';
}
}
主要措施如下:
(1) 以前是函数形式,准备用宏进行替换
(2) 由于简单加解密的特殊性, 准备采用字典表的形式进行加解密
unsigned char 是00000000 ~ 11111111范围
主要过程如下:
//生成加密字典
//生成字典
unsigned char dictionary[256];
int length = sizeof(dictionary)/sizeof(dictionary[0]);
for (int i = 0; i < length; ++i)
{ dictionary[i] = i;
dictionary[i] ^= '@';
}
//通过字典进行查找加密
unsigned char data[100];
for (int i = 0; i < 100; ++i)
{
data[i]=dictionary[data[i]];
}
测试代码:
//生成字典
unsigned char dictionary[256];
int length = sizeof(dictionary)/sizeof(dictionary[0]);
for (int i = 0; i < length; ++i)
{ dictionary[i] = i;
dictionary[i] ^= '@';
}
unsigned char test1[10000];
unsigned char test2[10000];
memcpy(test2, test1, 10000);
SYSTEMTIME sys;
GetLocalTime( &sys );
printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d/n",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds,sys.wDayOfWeek);
for (int i = 0; i <1000000; ++i)
{
for(int i = 0; i < 10000; ++i)
{
test1[i] ^= '@';
}
}
GetLocalTime( &sys );
printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d/n",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds,sys.wDayOfWeek);
system("PAUSE");
cout<<"Round Two"<<endl;
GetLocalTime( &sys );
printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d/n",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds,sys.wDayOfWeek);
for (int i = 0; i < 1000000; ++i)
{
for (int i = 0; i < 10000; ++i)
{
test2[i] = dictionary[test2[i]];
}
}
GetLocalTime( &sys );
printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d/n",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds,sys.wDayOfWeek);
测试结果如下:
以前的加解密耗时:1分零7秒,合67秒
查表法耗时: 24 + 17 = 41秒,
性能还是有较大的提升
里面有很多循环,如果用汇编写,效果会更好