【问题标题】:fastest way to read and parse text from stdin at the same time同时从标准输入读取和解析文本的最快方法
【发布时间】:2021-11-18 22:31:38
【问题描述】:

在 Linux 上使用 C++ 我正在解析(对于基于多重分隔符的单词)通过标准输入提供的大输入(没有其他方式)。

我使用 std::getline 读取 stdinput,然后使用以下伪代码解析该行。

for (std::string single_line; std::getline(std::cin, single_line);)
{
    std::string single_word;

    for (auto single_charecter : single_line)
    {
        //do parsing based on a delimiter and
        // create a word 
    }
}

我的问题是关于我使用 std::getline 然后一次解析一行一个字符的效率。

这不能通过其他函数调用或包括使用线程的方法来改进吗?

【问题讨论】:

  • 这能回答你的问题吗? How do I iterate over the words of a string?
  • @zerocukor287 不幸的是,这不是。花药特别要求一个解决方案是“请优先考虑优雅而不是效率”
  • 关于性能,没有任何理论可以超越三个规则:测量、测量和测量。
  • @MatG 我不能同意更多,希望有一些启发。
  • @p3t3 少数之一是最小化动态内存分配,其余变量太多:编译器、编译器版本、编译器标志、stdlib 实现、操作系统、操作系统版本、硬件……跨度>

标签: c++ linux time-complexity


【解决方案1】:

据我了解,您正在尝试解析文本输入并尝试根据分隔符创建单词。如果是这种情况,您不需要一次解析一行。您可以直接使用 stringstream 类和 getline 方法使用分隔符解析字符串试试这个 -

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::stringstream;

int main(){
    string text = "He said. The challenge Hector heard with joy, "
               "Then with his spear restrain'd the youth of Troy ";
    char del = ' ';
    vector<string> words{};

    stringstream sstream(text);
    string word;
    while (std::getline(sstream, word, del))
        words.push_back(word);

    for (const auto &str : words) {
        cout << str << endl;
    }

    return EXIT_SUCCESS;
}

输出 - 他 说。 这 ... 特洛伊

在此方法中,我们将文本字符串变量放入字符串流中,以便使用 getline 方法对其进行操作。 getline 提取字符直到找到给定的字符并将标记存储在字符串变量中。请注意,此方法只能在需要单个字符分隔符时应用。

【讨论】:

  • 这类似于我的解决方案,请注意我已经使用了 std::getline() 并且我在 stdin 上使用了它。另外,我有不止一个分隔符(需要使用所有“空格”和标点符号。
  • @p3t3 好吧,C++ 中没有通用的理想标记和解析。您需要针对您的特定协议和用例进行定制。因此,鉴于信息狭窄,您的问题过于宽泛。
  • 我的问题不是解析,当您解析时,您会遍历 O(n) 个元素。我在问关于标准输入的阅读。例如一次读取一个字节(使用 getchar())与 getline() 或 std::getline()。或者也许有一种方法可以读取一大块标准输入,而不是通过 getline() 读取它,直到它到达 "\n"
  • @p3t3 在这种情况下,我建议使用多线程。读入一个线程,将这些行传递给其他线程进行操作。或者,您可以使用 mmap。 mmap 使您可以像内存一样访问文件,因此您可以轻松地并行读取。看看这个Details on mmap
  • @SAIJAL 我同意使用多线程。将研究 mmap,我不确定它是否适用于标准输入。
猜你喜欢
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
相关资源
最近更新 更多