为什么C ++输出过慢得多比C? [英] Why C++ output is too much slower than C?

查看:101
本文介绍了为什么C ++输出过慢得多比C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我其实C ++的粉丝,但今天我想通了,我的程序很慢文件输出。所以,我设计了一个实验来比较C. C ++文件输出速度
假设我们有这一块code的:

I am actually a fan of C++, but today I figured out very slow file output of my program. So, I designed an experiment to compare speed of C++ file output with C. Suppose we have this piece of code :

int Num = 20000000;
vector <int> v;
for ( int i = 0; i < Num; i++ )
{
    v.push_back(i);
}

现在我运行两个单独的code,一个是C ++:

Now I run two separate code, one in C++ :

int now = time(0);
cout << "start" << endl;
ofstream fout("c++.txt");
for(size_t i = 0; i < v.size(); ++i)
{
    fout<< v[i] << endl;
}
fout.close();
cout << time(0) - now << endl;

,一个在C:

int now = time(0);
printf("start\n");
FILE *fp = fopen("c.txt", "w");
for(size_t i = 0; i < v.size(); ++i)
{
    fprintf(fp, "%d\n", v[i]);
}
fclose(fp);
printf("%ld\n", time(0) - now);

C ++程序的工作出奇慢!在我的系统,C计划在3秒内运行,而C ++程序大约需要50秒跑!
有没有合理的解释这个?

C++ program works surprisingly slower! On my system, C program runs in 3 seconds while C++ program takes about 50 seconds to run! Is there any reasonable explanation for this?

推荐答案

这是因为你是如何经常​​刷新流在C ++ code盘的可能性较大。插入 ENDL 到一个流中插入新行,并刷新缓冲区,而 fprintf中不会导致缓冲区刷新。

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.

所以,你的C ++例子执行20000000缓冲区刷新,而你的C例子只会刷新到磁盘时的文件句柄缓冲区已满。

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 ++输出过慢得多比C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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