提高ofstream的性能? [英] Improving performance of ofstream?

查看:61
本文介绍了提高ofstream的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FIFO 与一些并行进程进行通信.我正在用 read() 读取管道.我正在通过这样做写入命名管道:

I am communicating with some parallel processes using FIFOs. I am reading the pipe with read(). And I am writing to the named pipe by doing this:

ofstream pipe(namepipe);

pipe << data << endl;
pipe.close();

我一直注意到性能很糟糕!有时需要 40 毫秒.在我看来,这是一种极端的延迟.我读到使用 std::endl 会影响性能.我应该避免使用endl吗?

I have been noticing that the performance is horrible though! It takes like 40ms sometimes. It's an extreme latency in my opinion. I read that the use of std::endl can affect performance. Should I avoid using endl?

使用 ofstream 会影响性能吗?这种方法还有其他替代方法吗?

Does using ofstream affect performance? Are there any other alternatives to this method?

谢谢!

推荐答案

使用 fstream 处理大文件时,请确保使用流缓冲区 并且不要使用 endl(endl 刷新输出流).

When working with large files with fstream, make sure to use a stream buffer and don't use endl (endl flushes the output stream).

当没有设置缓冲区时,至少 MSVC 实现将一次 1 个字符复制到 filebuf(参见 streambuf::xsputn()>),这会使您的应用程序受 CPU 限制,从而导致 I/O 速率降低.

At least the MSVC implementation copies 1 char at a time to the filebuf when no buffer was set (see streambuf::xsputn()), which can make your application CPU-bound, which will result in lower I/O rates.

因此,在编写代码之前尝试将其添加到您的代码中:

So, try adding this to your code before doing the writing:

const size_t bufsize = 256*1024;
char buf[bufsize];
mystream.rdbuf()->pubsetbuf(buf, bufsize);

注意:您可以在此处找到完整的示例应用程序.子>

NB: You can find a complete sample application here.

这篇关于提高ofstream的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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