我只是不明白我做错了什么。下面显示的unicode tokenizer函数非常慢。也许有人可以给我一个提示如何加快速度? 感谢您的帮助。顺便说一句,ustring
是Glib::ustring
。 sep1
是隔板,不应该在结果 sep2
是隔板应该是单一令牌在结果C++ - Tokenizer非常慢
void tokenize(const ustring & u, const ustring & sep1,
const ustring & sep2, vector<ustring> & tokens) {
ustring s;
s.reserve(100);
ostringstream os;
gunichar c;
for (int i = 0; i < u.length(); i++) {
c = u[i];
if (sep1.find(c) != ustring::npos) {
tokens.push_back(s);
s = "";
}
else if (sep2.find(c) != ustring::npos) {
tokens.push_back(s);
s = "";
s.append(1, c);
tokens.push_back(s);
s = "";
}
else {
s.append(1, c);
}
}
if (s!="")
tokens.push_back(s);
}
我现在它改变到(现在的1之间和2秒)显示:
ustring s;
s.reserve(100);
ostringstream os;
gunichar c;
set<gunichar> set_sep1;
int i=0;
for (i=0;i<sep1.size();i++)
{
set_sep1.insert(sep1[i]);
}
set<gunichar> set_sep2;
for (i=0;i<sep2.size();i++)
{
set_sep2.insert(sep2[i]);
}
int start_index=-1;
int ulen=u.length();
i=0;
for (ustring::const_iterator it=u.begin();it!=u.end();++it)
{
c=*it;
if (set_sep1.find(c)!=set_sep1.end())
{
if (start_index!=-1 && start_index<i)
tokens.push_back(u.substr(start_index,i-start_index));
start_index=i+1;
s="";
}
else if (set_sep2.find(c)!=set_sep2.end())
{
tokens.push_back(s);
s="";
tokens.push_back(s);
start_index=i+1;
s="";
}
i++;
}
if (start_index!=-1 && start_index<ulen)
tokens.push_back(u.substr(start_index,ulen-start_index));
有一件事你可以做的是不使用频繁'.append()'调用,并开始使用索引。即将标记开始的索引存储在一个变量中,并且一旦遇到标记的结尾,就执行'tokens.push_back(u.substr(start,end - start))'。使用迭代器可能比这个方法更好... –
你是否分析了你的代码?探查器在哪里找到瓶颈? –