gpt4 book ai didi

C++ - 为什么分词器从文件中读取行这么慢?

转载 作者:太空狗 更新时间:2023-10-29 20:05:39 25 4
gpt4 key购买 nike

我试图从文件中读取 200,000 条记录,然后使用 tokenizer 解析字符串并删除每个部分周围的引号。但是与正常读取字符串相比,运行时间非常长。仅仅读取这些记录就需要 25 秒(每条记录 0.0001 秒????)。我的编程有什么问题吗?如果没有,是否有更快的方法?

int main()
{
int counter = 0;
std::string getcontent;
std::vector<std::string> line;
std::vector< std::vector<std::string> > lines;

boost::escaped_list_separator<char> sep( '\\', '*', '"' ) ;
boost::tokenizer<> tok(getcontent);

std::ifstream openfile ("test.txt");

if(openfile.is_open())
{
while(!openfile.eof())
{
getline(openfile,getcontent);

// THIS LINE TAKES A LOT OF TIME
boost::tokenizer<> tok(getcontent);

for (boost::tokenizer<>::iterator beg=tok.begin(); beg!=tok.end(); ++beg){
line.push_back(*beg);
}

lines.push_back(line);
line.clear();
counter++;
}
openfile.close();
}
else std::cout << "No such file" << std::endl;

return 0;
}

最佳答案

至少如果我没看错的话,我想我会采取更像 C 语言的方法。我不是读一行,然后把它分解成标记,然后去掉你不想要的字符,而是一次读一个字符,然后根据我读到的字符,决定是否将它添加到当前token,结束token并将其添加到当前行,或结束该行并将其添加到行 vector :

#include <vector>
#include <string>
#include <stdio.h>
#include <time.h>

std::vector<std::vector<std::string> > read_tokens(char const *filename) {
std::vector<std::vector<std::string> > lines;
FILE *infile= fopen(filename, "r");

int ch;

std::vector<std::string> line;
std::string token;

while (EOF != (ch = getc(infile))) {
switch(ch) {
case '\n':
lines.push_back(line);
line.clear();
token.clear();
break;
case '"':
break;
case '*':
line.push_back(token);
token.clear();
break;
default:
token.push_back(ch);
}
}
return lines;
}

int main() {
clock_t start = clock();
std::vector<std::vector<std::string> > lines = read_tokens("sample_tokens.txt");
clock_t finish = clock();
printf("%f seconds\n", double(finish-start)/CLOCKS_PER_SEC);
return 0;
}

对一个文件进行快速测试,该文件包含您在评论中提供的示例的 200K 多个拷贝,它正在读取数据并(显然)用 gcc 在 ~3.5 秒或用 VC++ 在 ~4.5 秒内标记数据。如果看到任何东西变得更快(至少没有更快的硬件),我会感到有点惊讶。

顺便说一句,这与您最初所做的一样处理内存,这(至少在我看来)是非常有力的证据,表明在 vector 中管理内存可能不是主要瓶颈。

关于C++ - 为什么分词器从文件中读取行这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12344722/

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