我有以下片段。
#include <iostream>
#include <sstream>
#include <chrono>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/classic.hpp>
namespace qi = boost::spirit::qi;
namespace classic = boost::spirit::classic;
template<typename T>
void output_time(const T& end, const T& begin)
{
std::cout << std::chrono::duration_cast<std::chrono::seconds>(
end - begin).count() << std::endl;
}
template<typename Iter>
struct qi_grammar : public qi::grammar<Iter>
{
qi_grammar():qi_grammar::base_type(rule_)
{
rule_ = *string_;
string_ = qi::char_('"') >> *(qi::char_ - '"') >> qi::char_('"');
}
qi::rule<Iter> rule_;
qi::rule<Iter> string_;
};
template<typename Iter>
struct classic_grammar : public classic::grammar<classic_grammar<Iter>>
{
template<typename ScannerT>
struct definition
{
definition(const classic_grammar&)
{
rule = *string_;
string_ = classic::ch_p('"') >> *(classic::anychar_p - '"') >> classic::ch_p('"');
}
classic::rule<ScannerT> rule, string_;
const classic::rule<ScannerT>& start() const { return rule; }
};
};
template<typename Iter>
void parse(Iter first, Iter last, const qi_grammar<Iter>& prs)
{
auto start = std::chrono::system_clock::now();
for (int i = 0; i < 100; ++i)
{
Iter next = first;
if (!qi::parse(next, last, prs) || next != last)
{
assert(false);
}
}
auto finish = std::chrono::system_clock::now();
output_time(finish, start);
}
template<typename Iter>
void parse_c(Iter first, Iter last, const classic_grammar<Iter>& prs)
{
auto start = std::chrono::system_clock::now();
for (int i = 0; i < 100; ++i)
{
auto info = classic::parse(first, last, prs);
if (!info.hit) assert(false);
}
auto finish = std::chrono::system_clock::now();
output_time(finish, start);
}
int main()
{
qi_grammar<std::string::const_iterator> qi_lexeme;
classic_grammar<std::string::const_iterator> classic_lexeme;
std::stringstream ss;
for (int i = 0; i < 1024 * 500; ++i)
{
ss << "\"name\"";
}
const std::string s = ss.str();
std::cout << "Size: " << s.size() << std::endl;
std::cout << "Qi" << std::endl;
parse(s.begin(), s.end(), qi_lexeme);
std::cout << "Classic" << std::endl;
parse_c(s.begin(), s.end(), classic_lexeme);
}
结果是
forever@pterois:~/My_pro1/cpp_pro$ ./simple_j
Size: 3072000
Qi
0
Classic
1
所以,qi 解析比经典快。但是当我将 string_ 规则的属性更改为 std::string() (即qi::rule<Iter, std::string()> string_;
)时,我有
forever@pterois:~/My_pro1/cpp_pro$ ./simple_j
Size: 3072000
Qi
19
Classic
1
它非常非常慢。我做错了什么?谢谢。
编译器:gcc 4.6.3。提升 - 1.48.0。标志:-std=c++0x -O2。在 LWS 上的结果是相同的。
char_ ie 语义动作的使用
string_ = qi::char_('"') >> *(qi::char_[boost::bind(&some_f, _1)] - '"')
>> qi::char_('"')[boost::bind(&some_clear_f, _1)];
提高性能,但我也在寻找另一种解决方案,如果它存在的话。