C/C++ Linux:将固定内存块写入文件的最快速度(1 Hz)
在 Linux 系统上,我有一块 7MB 的固定大小的内存块(没有增长),我在实时应用程序中刷新其内容。
我需要每秒将这块内存写入磁盘(同一文件)一次。
考虑到现代(2011 年末)CPU 和 HDD,实现此功能的最有效方法是什么?我不在乎写入是否实际上需要一些时间,但由于这是一个实时应用程序,我需要尽快返回到正在运行的应用程序。
我应该尝试什么方法?
我的基线是标准基线 fopen()、二进制 fwrite()、fclose() 循环。
我读过 mmap() 可能有用。也许是异步 I/O?我还应该对其他方法进行基准测试吗?从你的头脑中,你认为哪种方法最快?
On a Linux system, I have one 7MB chunk of memory of fixed size (no growth) whose contents I refresh in a real-time application.
I need to write this chunk of memory to disk (same file) once per second.
Taking into consideration modern (late 2011) CPUs and HDDs, what is the most efficient way to implement this functionality? I don't care if the write actually takes some time, but as this is a real-time app, I need to return to the running app ASAP.
What methodologies should I be trying?
My baseline is a standard baseline fopen(), binary fwrite(), fclose() cycle.
I have read that mmap() might be useful. Maybe asynchronous I/O? Are there other methodologies that I should be benchmarking? Off the top of your head, which methodology do you think would be fastest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
mmap(2)
是正确的选择。当您想编写它时,只需使用MS_ASYNC
调用msync(2)
即可。mmap(2)
is the way to go. Just callmsync(2)
withMS_ASYNC
when you want to write it.我将结合提到的两种方法:我将使用
mmap
来映射内存到文件,然后设置一个单独的线程(优先级较低)
每秒
msync
它。 (在这种情况下,实际参数msync
不太重要;你不需要MS_ASYNC
,因为你不会阻塞主线程。)
另一个可能值得尝试的替代方案是异步 IO。
从我的文档中我不清楚如果你不这样做会发生什么
但是,恢复结果,因此您可能需要某种收割者代码
以防止资源丢失。 (异步 IO 似乎未指定
在 Posix 中,恕我直言,这是避免使用它的一个很好的理由。)
I'd combine the two approaches mentionned: I'd use
mmap
to map thememory to the file, then set up a separate thread (with lower priority)
to
msync
it every second. (In this case, the actual arguments tomsync
are not too important; you don't needMS_ASYNC
, since youwon't be blocking the main thread.)
Another alternative possibly worth trying would be asynchronous IO.
It's not clear to me from my documentation what happens if you never
recover the results, however, so you may need some sort of reaper code
to prevent lost resources. (Asynchronous IO seems rather underspecified
in Posix, which IMHO is a good reason to avoid it.)