C ++ ifstream.getline()比Java的BufferedReader.readLine显著慢()? [英] C++ ifstream.getline() significantly slower than Java's BufferedReader.readLine()?

查看:492
本文介绍了C ++ ifstream.getline()比Java的BufferedReader.readLine显著慢()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在重写我的一个Android应用程序采取NDK的优势和它做每次都是开一个1.5MB的文本文件(大约150K线)的第一件事情的过程中,把每一行在数据结构中。当我使用Java的BufferedReader.readLine(),从SD卡读取文件做这个手术大约需要2.5秒。这里的code我用这样的:

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分钟的时间相同的文件。这里的code我用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 ++ pretty的生疏,但想不到的增加阅读时间任何合乎逻辑的解释。有一段时间,我想这可能是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);
}

我没有测试此code,但你可以尝试一下,看看它是否有差别。

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

这篇关于C ++ ifstream.getline()比Java的BufferedReader.readLine显著慢()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆