出于某种原因,我决定制作一个非常简单的应用程序,显示从1到1000000的所有数字。我注意到显示结果比存储它们要花费更长的时间。我以为存储所有值需要比显示它们花费更长的时间。我还记得阅读过一篇文章,如果我没记错的话,在控制台应用程序中,用户输入和从文本文件中读取没有真正的区别,所以我认为显示和存储是一样的。
有人能解释一下这是为什么吗?根据我正在阅读的书中,ofstream 与 cout 非常相似,所以我不明白为什么它需要更长的时间。
为什么使用 cout 显示结果比使用 ofstream 将结果存储在文本文件中要慢?
cout = 169.168秒
ofstream = 3.473秒
ofstream 方法
为什么使用 cout 显示结果比使用 ofstream 将结果存储在文本文件中要慢?
cout = 169.168秒
ofstream = 3.473秒
ofstream 方法
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
namespace patch //used to patch some C++11 functions not included in mingw 4.7 // to_string
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
using namespace patch;
using namespace std;
int main()
{
int minimumRange = 1; //sets minimum number in range
int maximumRange = 1000000; // sets maximum number in range
string strRanges = to_string(minimumRange) + "-" + to_string(maximumRange); //appends string names
ofstream myRange;
myRange.open(strRanges + ".txt");
for (int i = minimumRange; i<=maximumRange; ++i)
{
myRange << to_string(i) << "\n";
}
myRange.close();
return 0;
}
cout method
#include <iostream>
using namespace std;
int main()
{
int minimumRange = 1;
int maximumRange = 1000000;
for (int i = minimumRange; i<=maximumRange; ++i)
{
cout << i << "\n"; //using "/n" instead of endl; for speed purposes
}
return 0;
}
std::cout
版本执行./program > /dev/null
。 - user1508519std::cout
的性能之前,请将其从 C 标准流中分离。参考链接:https://dev59.com/PV_Va4cB1Zd3GeqPWLy6#9026594 - dypmyRange.open(strRanges + ".txt");
是C++11(使用std::string
打开文件)--只有在尝试编译它时才发现需要加上-std=c++11
;) - dyp