如何在 C++ 中从流执行快速格式化输入?

发布于 2024-07-14 15:28:39 字数 208 浏览 6 评论 0原文

情况是:有一个文件有14 294 508个无符号整数和13 994 397个浮点数(需要读取double)。 文件总大小约为 250 MB。

使用 std::istream 大约需要 30 秒。 将数据从文件读取到内存(仅复制字节,无需格式化输入)要快得多。 有没有什么办法可以在不改变文件格式的情况下提高阅读速度呢?

The situation is: there is a file with 14 294 508 unsigned integers and 13 994 397 floating-point numbers (need to read doubles). Total file size is ~250 MB.

Using std::istream takes ~30sec. Reading the data from file to memory (just copying bytes, without formatted input) is much faster. Is there any way to improve reading speed without changing file format?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

放我走吧 2024-07-21 15:28:39

你需要使用STL风格的i/o吗? 您必须查看这篇来自专家之一。 它是由 Dietmar Kuhl 开发的专用 iostream

我不想建议这样做,但请看一下 C 格式的 I/O 例程。 另外,你是一口气读完整个文件吗?

Do you need to use STL style i/o? You must check out this excellent piece of work from one of the experts. It's a specialized iostream by Dietmar Kuhl.

I hate to suggest this but take a look at the C formatted i/o routines. Also, are you reading in the whole file in one go?

怎言笑 2024-07-21 15:28:39

您可能还想查看 Matthew Wilson 的 FastFormat 库:

我还没有使用过它,但他提出了一些令人印象深刻的主张,而且我发现他的许多其他作品值得研究和使用(有时也值得窃取)。

You might also want to look at Matthew Wilson's FastFormat library:

I haven't used it, but he makes some pretty impressive claims and I've found a lot of his other work to be worth studying and using (and stealing on occasion).

无名指的心愿 2024-07-21 15:28:39

你还没有指定格式。 您可以对其进行内存映射,或者可以读取非常大的块并以批处理算法进行处理。

另外,您还没有说您是否确定要读取该文件的文件和进程将位于同一平台上。 如果大端进程写入它而小端进程读取它,反之亦然,则它将不起作用。

You haven't specified the format. It's possible that you could memory map it, or could read in very large chunks and process in a batch algorithm.

Also, you haven't said whether you know for sure that the file and process that will read it will be on the same platform. If a big-endian process writes it and a little-endian process reads it, or vice versa, it won;t work.

沙与沫 2024-07-21 15:28:39

与“通用”读取方法相比,自行解析输入(atoi 和 atof)通常可以将速度提高至少两倍。

Parsing input by yourself (atoi & atof), usually boosts speed at least twice, compared to "universal" read methods.

坚持沉默 2024-07-21 15:28:39

快速而肮脏的方法是将文件转储到标准 C++ 字符串中,然后在其上使用 stringstream:

#include <sstream>
// Load file into string file_string
std::stringstream s( file_string );
int x; float y;
s >> x >> y;

这可能不会给您带来太大的性能改进(通过避免 iostreams,您将获得更大的加速),但它是很容易尝试,而且可能会足够快。

Something quick and dirty is to just dump the file into a standard C++ string, and then use a stringstream on it:

#include <sstream>
// Load file into string file_string
std::stringstream s( file_string );
int x; float y;
s >> x >> y;

This may not give you much of a performance improvement (you will get a larger speed-up by avoiding iostreams), but it's very easy to try, and it may be faster enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文