据说Ragel生成的自动机程序,速度飞快,特地测试了一下,所得结果如下。
  
 测试环境:      VC6 + Release下编译
 测试规模:      一亿次
 测试用例:      Ragel编译r_atoi.rl文件 vs crt lib的 atoi函数
 测试结果:
    | Ragel的编译选项 | 时间(毫秒) | 
  | crt lib 的atoi | 5218 | 
  | -T0 | 31500 | 
  | -T1 | 26328 | 
  | -F0 | 17797 | 
  | -F1 | 13578 | 
  | -G0 | 13203 | 
  | -G1 | 10531 | 
  | -G2 | 5422 | 
 -G2选项编译后生成的代码,速度确实强大,基本上和atoi库函数没有多少差别,要知道atoi可是crt lib里的啊,已经精到不能再精,优化到不能再优化了。
 PS:很久前,我曾用汇编写了个my_memcpy,然后和crt lib的memcpy比速度,结果只有它的一半效率,然后用C写个再比,下滑到了1/6,从此以后我再也不怀疑crt lib的效率了,取而代之的是异常崇拜。
  
 l        Ragel的编译选项
 
  
 l        测试程序如下
  
 #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生成的状态机
     }
     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;
 }
  
 自动 生成的自动机图形
  