據(jù)說(shuō)Ragel生成的自動(dòng)機(jī)程序,速度飛快,特地測(cè)試了一下,所得結(jié)果如下。
測(cè)試環(huán)境: VC6 + Release下編譯
測(cè)試規(guī)模: 一億次
測(cè)試用例: Ragel編譯r_atoi.rl文件 vs crt lib的 atoi函數(shù)
測(cè)試結(jié)果:
Ragel的編譯選項(xiàng) | 時(shí)間(毫秒) |
crt lib 的atoi | 5218 |
-T0 | 31500 |
-T1 | 26328 |
-F0 | 17797 |
-F1 | 13578 |
-G0 | 13203 |
-G1 | 10531 |
-G2 | 5422 |
-G2選項(xiàng)編譯后生成的代碼,速度確實(shí)強(qiáng)大,基本上和atoi庫(kù)函數(shù)沒(méi)有多少差別,要知道atoi可是crt lib里的啊,已經(jīng)精到不能再精,優(yōu)化到不能再優(yōu)化了。
PS:很久前,我曾用匯編寫了個(gè)my_memcpy,然后和crt lib的memcpy比速度,結(jié)果只有它的一半效率,然后用C寫個(gè)再比,下滑到了1/6,從此以后我再也不懷疑crt lib的效率了,取而代之的是異常崇拜。
l Ragel的編譯選項(xiàng)

l 測(cè)試程序如下
#include <windows.h>
int main()
{
char* p_sz = "784215491\n";
long val = 0;
long tick = GetTickCount();
for (int i = 0; i < 100000000; ++i)
{
val = atoi(p_sz);
//val = r_atoi(p_sz);//---- Ragel生成的狀態(tài)機(jī)
}
tick = GetTickCount() - tick;
printf("%ld\n", tick);
return 0;
}
l r_atoi.rl如下
/*
* Convert a string to an integer.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
%%{
machine r_atoi;
write data;
}%%
long r_atoi( char *str )
{
char *p = str, *pe = str + strlen( str );
int cs;
long val = 0;
bool neg = false;
%%{
action see_neg {
neg = true;
}
action add_digit {
val = val * 10 + (fc - '0');
}
main :=
( '-'@see_neg | '+' )? ( digit @add_digit )+
'\n';
# Initialize and execute.
write init;
write exec;
}%%
if ( neg )
val = -1 * val;
if ( neg )
val = -1 * val;
if ( cs < r_atoi_first_final )
fprintf( stderr, "r_atoi: there was an error\n" );
return val;
};
#define BUFSIZE 1024
/*
int main()
{
char buf[BUFSIZE];
while ( fgets( buf, sizeof(buf), stdin ) != 0 ) {
long value = r_atoi( buf );
printf( "%lld\n", value );
}
return 0;
}
*/
#include <windows.h>
#include <limits.h>
int main()
{
char* p_sz = "784215491\n";
long val = 0;
long tick = GetTickCount();
for (int i = 0; i < 100000000; ++i)
{
val = r_atoi(p_sz);
}
tick = GetTickCount() - tick;
printf("%ld\n", tick);
return 0;
}
自動(dòng) 生成的自動(dòng)機(jī)圖形
