stackoverflow : Why C++ output is too much slower than C?

来源:互联网 发布:数据分析师知乎 编辑:程序博客网 时间:2024/05/18 00:29

 

ANSWER:

It's likely because of how often you are flushing the stream to disk in the C++ code. Inserting endl into a stream inserts a new line and flushes the buffer, while fprintf doesn't cause a buffer flush.

So your C++ example performs 20,000,000 buffer flushes while your C example will only flush to disk when the file handles buffer is full.

 

知识点:C++里面endl用来换行的时候,会刷新缓冲区,将数据写入磁盘,从而造成了效率的损失,而C中的fprintf函数则不会。解决方法是用 \n 代替 endl


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>