C++ ifstream.getline() 明显慢于 Java 的 BufferedReader.readLine()?

我正在重写我的一个 Android 应用程序以利用 NDK,它每次要做的第一件事就是打开一个 1.5MB 的文本文件(大约 150k 行)并将每一行在数据结构中.当我使用 Java 的 BufferedReader.readLine() 执行此操作时,从 SD 卡读取文件需要大约 2.5 秒.这是我用于此的代码:

I'm in the process of rewriting one of my Android applications to take advantage of the NDK and one of the first things it has to do every time is open a 1.5MB text file (approximately 150k lines) and put every line in a data structure. When I did this operation using Java's BufferedReader.readLine(), reading the file from the SD card takes ~2.5 seconds. Here's the code I used for this:

try {
    BufferedReader br = new BufferedReader(new FileReader("/sdcard/testfile.txt"));
    String thisLine;
    while ((thisLine = br.readLine()) != null) {
        Log.d(TAG, thisLine);
    }
} catch (IOException e) {
    //Log error
}

将 C++ 与 ifstream 一起使用需要更长的时间……对于同一个文件,大约需要 3 分钟.这是我在 C++ 中使用的代码:

Using C++ with ifstream takes MUCH longer...around 3 minutes for the same file. Here's the code I used in C++:

char buffer[256];
ifstream ifs;
ifs.open("/sdcard/testfile.txt", ifstream::in);
if (ifs.is_open()) {
    while (!ifs.eof()) {
        ifs.getline (buffer,100);
        LOGD(buffer);
    }
}

我对 C++ 相当生疏,但对于增加的读取时间想不出任何合乎逻辑的解释.有一段时间我认为这可能是 LOGD 功能,但我尝试将其完全去掉,阅读时间并没有太大帮助.有没有人对问题可能有任何想法?有没有更快的方法在 C++ 中逐行读取文件?谢谢.

I'm pretty rusty on C++, but can't think of any logical explanation for the increased read time. For a while I thought it might be the LOGD function, but I tried taking that out altogether and the read time wasn't really helped much at all. Does anyone have any ideas on what the issue could be? Is there any faster way to read a file line by line in C++? Thanks.

推荐答案

一个想法是 stdio 同步可能会减慢你的速度.那可以关掉.我不知道这是否会导致所有差异,但您可以尝试.此外,您没有正确使用 eof() .最后,我会使用 getline()

One thought is the stdio synchronization might be slowing you down. That can be turned off. I don't know if that would account for all of the difference, but you could try. Also, you're not using eof() correctly. Finally, I'd use the std::string version of getline()

std::ios::sync_with_stdio(false);
ifstream ifs("/sdcard/testfile.txt");
std::string line;
while (getline(ifs, line))
{
    LOGD(line);
}

我还没有测试过这段代码,但你可以试试看它是否有所作为.

I haven't tested this code, but you can try it and see if it makes a difference.

相关文章