Very poor boost::lexical_cast performance

后端 未结 9 1004
别那么骄傲
别那么骄傲 2020-11-27 10:31

Windows XP SP3. Core 2 Duo 2.0 GHz. I\'m finding the boost::lexical_cast performance to be extremely slow. Wanted to find out ways to speed up the code. Using /O2 optimizati

9条回答
  •  萌比男神i
    2020-11-27 11:27

    I use this very fast solution for POD types...

    namespace DATATYPES {
    
        typedef std::string   TString;
        typedef char*         TCString;
        typedef double        TDouble;
        typedef long          THuge;
        typedef unsigned long TUHuge;
    };
    
    namespace boost {
    
    template
    inline const DATATYPES::TString lexical_castNumericToString(
    
                                    const TYPE& arg, 
                                    const DATATYPES::TCString fmt) {
    
        enum { MAX_SIZE = ( std::numeric_limits::digits10 + 1 )  // sign
                                                                + 1 }; // null
        char buffer[MAX_SIZE] = { 0 };
    
        if (sprintf(buffer, fmt, arg) < 0) {
            throw_exception(bad_lexical_cast(typeid(TYPE),
                                             typeid(DATATYPES::TString)));
        }
        return ( DATATYPES::TString(buffer) );
    }
    
    template
    inline const TYPE lexical_castStringToNumeric(const DATATYPES::TString& arg) {
    
        DATATYPES::TCString end = 0;
        DATATYPES::TDouble result = std::strtod(arg.c_str(), &end);
    
        if (not end or *end not_eq 0) {
            throw_exception(bad_lexical_cast(typeid(DATATYPES::TString),
                                             typeid(TYPE)));
        }
        return TYPE(result);
    }
    
    template<>
    inline DATATYPES::THuge lexical_cast(const DATATYPES::TString& arg) {
        return (lexical_castStringToNumeric(arg));
    }
    
    template<>
    inline DATATYPES::TString lexical_cast(const DATATYPES::THuge& arg) {
        return (lexical_castNumericToString(arg,"%li"));
    }
    
    template<>
    inline DATATYPES::TUHuge lexical_cast(const DATATYPES::TString& arg) {
        return (lexical_castStringToNumeric(arg));
    }
    
    template<>
    inline DATATYPES::TString lexical_cast(const DATATYPES::TUHuge& arg) {
        return (lexical_castNumericToString(arg,"%lu"));
    }
    
    template<>
    inline DATATYPES::TDouble lexical_cast(const DATATYPES::TString& arg) {
        return (lexical_castStringToNumeric(arg));
    }
    
    template<>
    inline DATATYPES::TString lexical_cast(const DATATYPES::TDouble& arg) {
        return (lexical_castNumericToString(arg,"%f"));
    }
    
    } // end namespace boost
    

提交回复
热议问题