牵着老婆满街逛

严以律己,宽以待人. 三思而后行.
GMail/GTalk: yanglinbo#google.com;
MSN/Email: tx7do#yahoo.com.cn;
QQ: 3 0 3 3 9 6 9 2 0 .

快速atof()函数

/*shamelessly ripped from irrlicht3d engine.*/
const float fast_atof_table[] = {
    
0.f,
   
0.1f,
   
0.01f,
   
0.001f,
   
0.0001f,
   
0.00001f,
   
0.000001f,
   
0.0000001f,
   
0.00000001f,
   
0.000000001f,
   
0.0000000001f,
   
0.00000000001f,
   
0.000000000001f,
   
0.0000000000001f,
   
0.00000000000001f,
   
0.000000000000001f
};
inline 
const char* fast_atof_move_const(const char* c, float& out)
{
    
bool inv = false;
    
char *t;
    
float f;
    
if (*c==-')
    {
        c
++;
        inv 
= true;
    }
    f 
= (float)strtol(c, &t, 10);
    c 
= t;
    
if (*== ‘.’)
    {
        c
++;

        
float pl = (float)strtol(c, &t, 10);
        pl 
*= fast_atof_table[t-c];

        f 
+= pl;
        c 
= t;

        
if (*== ‘e’)
        {
            
++c;
            
float exp = (float)strtol(c, &t, 10);
            f 
*= (float)pow(10.0f, exp);
            c 
= t;
        }
    }

    
if (inv)
        f 
*= -1.0f;

    
out = f;
    
return c;
}

inline 
float fast_atof(const char* c)
{
    
float ret;
    fast_atof_move_const(c, ret);
    
return ret;

posted on 2007-07-21 12:59 杨粼波 阅读(798) 评论(2)  编辑 收藏 引用

评论

# re: 快速atof()函数 2007-07-22 11:39 muf

又是strtol又是pow,尽管用了查表,但是乘法照样没少,就省了一个除法,为什么认为这个算法是快速的??  回复  更多评论   

# re: 快速atof()函数 2014-04-15 16:57 大漠

除法很耗时间的,上述代码经实测,使用vs2005 release编译在i3 cpu上,可以比atof函数快4倍左右,但atof返回的是双精度浮点。  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理