gpt4 book ai didi

C++-分词器极慢

转载 作者:行者123 更新时间:2023-11-28 00:14:35 25 4
gpt4 key购买 nike

我只是不明白我做错了什么。下面显示的 unicode 分词器函数非常非常慢。也许有人可以给我提示如何加快速度?谢谢你的帮助。顺便说一句,ustringGlib::ustringsep1 是不应出现在结果中的分隔符sep2 是结果中应该是单个标记的分隔符

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));

最佳答案

这里可能“非常非常慢”的事情是:

  1. ustring::length()
  2. ustring::append()
  3. 通过 operator[] 随机访问 ustring :例如c=u[i];

尝试以下操作:

  1. 不是在循环中调用 u.length(),而是将长度存储在一个变量中,然后在循环中与该变量进行比较
  2. 将当前标记的字符附加到 ostringstreamwostringstream 而不是 ustring
  3. 使用迭代器而不是涉及随机访问的索引遍历 ustring

例子:

for(ustring::const_iterator it = u.cbegin(); it != u.cend(); it++)
{
c = *it;
//implementation follows
}

关于C++-分词器极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31180605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com