C 和 C++ 样式文件 IO 之间的性能差异 [英] Performance Difference Between C and C++ Style File IO

查看:29
本文介绍了C 和 C++ 样式文件 IO 之间的性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直听说 C++ 文件 I/O 操作比 C 风格 I/O 慢得多.但是我没有找到任何关于它们实际上有多慢的实用参考,所以我决定在我的机器上测试它(Ubuntu 12.04、GCC 4.6.3、ext4 分区格式).

I've always heard that C++ file I/O operations are much much slower than C style I/O. But I didn't find any practical references on comparatively how slow they actually are, so I decided to test it in my machine (Ubuntu 12.04, GCC 4.6.3, ext4 partition format).

首先我在磁盘中写入了一个 ~900MB 的文件.

First I wrote a ~900MB file in the disk.

C++ (ofstream):163s

C++ (ofstream): 163s

ofstream file("test.txt");
    
for(register int i = 0; i < 100000000; i++) 
    file << i << endl;

C (fprintf):12s

FILE *fp = fopen("test.txt", "w");
    
for(register int i = 0; i < 100000000; i++) 
    fprintf(fp, "%d
", i);

我期待这样的输出,它表明在 C++ 中写入文件比在 C 中慢得多.然后我使用 C 和 C++ I/O 读取同一个文件.是什么让我惊叹从文件读取时性能几乎没有差异.

I was expecting such output, it shows that writing to a file is much slower in C++ than in C. Then I read the same file using C and C++ I/O. What made me exclaimed that there is almost no difference in performance while reading from file.

C++ (ifstream):12s

int n;
ifstream file("test.txt");

for(register int i = 0; i < 100000000; i++) 
    file >> n;

C (fscanf):12s

FILE *fp = fopen("test.txt", "r");
    
for(register int i = 0; i < 100000000; i++) 
    fscanf(fp, "%d", &n);

那么,为什么使用流执行写入要花这么长时间?或者,为什么使用流读取比写入快?

So, why is taking so long to execute writing using stream? Or, why reading using stream is so fast compared to writing?

结论:罪魁祸首是 std::endl,正如答案和评论所指出的那样.换线<代码>文件<<我<<endl;到<代码>文件<<我<<' '; 已将运行时间从 163 秒减少到 16 秒.

Conclusion: The culprit is the std::endl, as the answers and the comments have pointed out. Changing the line file << i << endl; to file << i << ' '; has reduced running time to 16s from 163s.

推荐答案

您正在使用 endl 打印换行符.这就是问题所在,因为它更多不仅仅是打印换行符 —endl刷新缓冲区,这是一个昂贵的操作(如果你在每次迭代中都这样做).

You're using endl to print a newline. That is the problem here, as it does more than just printing a newline — endl also flushes the buffer which is an expensive operation (if you do that in each iteration).

如果您的意思是这样,请使用 :

Use if you mean so:

file << i << '
';

此外,必须在发布模式下编译您的代码(即打开优化).

And also, must compile your code in release mode (i.e turn on the optimizations).

这篇关于C 和 C++ 样式文件 IO 之间的性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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