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

查看:137
本文介绍了性能差异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 then 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\n", i);

我期待这样的输出,它表明写入文件位于C慢得多++的C.然后我读使用C和C ++的I / O相同的文件。是什么让我惊呼在性能几乎没有区别,而从文件中读取。

I was expecting such output, it shows that writing to a file is much slower in C++ the 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

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 ,因为答案和评论人士指出。转产
文件&LT;&LT; I&LT;&LT; ENDL;

文件&LT;&LT; I&LT;&LT;的'\\ n'; 已从器163s缩短运行时间为16S

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 << '\n'; has reduced running time to 16s from 163s.

推荐答案

您正在使用 ENDL 来打印一个换行符。这是这里的问题,因为它的更多的不仅仅是打印一个换行符&MDASH; 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).

使用 \\ n 如果你的意思是这样:

Use \n if you mean so:

file << i << '\n';

而且,必须编译在释放模式的code(即打开优化)。

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

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

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