我正在研究一个状态机,它应该提取表单的函数调用
/* I am a comment */
//I am a comment
pref("this.is.a.string.which\"can have QUOTES\"", 123456);
其中提取的数据将是 pref("this.is.a.string.which\"can have QUOTES\"", 123456);
从一个文件。目前,要处理一个 41kb 的文件,这个过程需要将近一分半钟。我对这个有限状态机有什么严重误解吗?
#include <boost/algorithm/string.hpp>
std::vector<std::string> Foo()
{
std::string fileData;
//Fill filedata with the contents of a file
std::vector<std::string> results;
std::string::iterator begin = fileData.begin();
std::string::iterator end = fileData.end();
std::string::iterator stateZeroFoundLocation = fileData.begin();
std::size_t state = 0;
for(; begin < end; begin++)
{
switch (state)
{
case 0:
if (boost::starts_with(boost::make_iterator_range(begin, end), "pref(")) {
stateZeroFoundLocation = begin;
begin += 4;
state = 2;
} else if (*begin == '/')
state = 1;
break;
case 1:
state = 0;
switch (*begin)
{
case '*':
begin = boost::find_first(boost::make_iterator_range(begin, end), "*/").end();
break;
case '/':
begin = std::find(begin, end, L'\n');
}
break;
case 2:
if (*begin == '"')
state = 3;
break;
case 3:
switch(*begin)
{
case '\\':
state = 4;
break;
case '"':
state = 5;
}
break;
case 4:
state = 3;
break;
case 5:
if (*begin == ',')
state = 6;
break;
case 6:
if (*begin != ' ')
state = 7;
break;
case 7:
switch(*begin)
{
case '"':
state = 8;
break;
default:
state = 10;
break;
}
break;
case 8:
switch(*begin)
{
case '\\':
state = 9;
break;
case '"':
state = 10;
}
break;
case 9:
state = 8;
break;
case 10:
if (*begin == ')')
state = 11;
break;
case 11:
if (*begin == ';')
state = 12;
break;
case 12:
state = 0;
results.push_back(std::string(stateZeroFoundLocation, begin));
};
}
return results;
}
比利3
编辑:嗯,这是我见过的最奇怪的事情之一。我刚刚重建了该项目,它再次正常运行。奇怪。
最佳答案
除非您的 41 kb 文件主要是评论或首选项,否则它将花费大部分时间处于状态 0。对于处于状态 0 的每个字符,您至少进行两次函数调用。
if (boost::starts_with(boost::make_iterator_range(begin, end), "pref(")) {
您可以通过预测试查看当前字符是否为“p”来加快速度
if (*begin == 'p' && boost::starts_with(boost::make_iterator_range(begin, end), "pref(")) {
如果字符不是“p”,则无需进行任何函数调用。特别是不创建迭代器,这可能是花费时间的地方。
关于c++ - 为什么我的有限状态机需要这么长时间才能执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2474548/