From a stream faster than cout? || Storage faster than visual output

For some reason, I decided to make a very simple application that displays all numbers from 1 to 1,000,000. I noticed that it takes more time to display the results than to store them. I suggested that saving all the values ​​would take longer than displaying them. I also remember that I read, if I remember correctly, that there is no difference between user input and reading from a text file in a console application, so I assumed that the display and storage are the same. Can someone explain why this is so? According to the book I'm reading, the stream is really like cout, so I don’t understand why it takes longer.

Why is displaying results slower with using coutthan storing results in a text file with ofstream?

cout = 169.168 seconds

ofstream = 3.473 seconds

flow method

#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;
}
+4
source share
1 answer

On many systems, it coutis just an instance ostreamdisplaying a file CON.

The fact is that ostream does not write anything.

Its purpose is to convert any supported types (maninly: const char*, std::string, int, long..., double...) in "sequence of characters", which must be placed in the buffer (cm. std::streambuf).

In this sense, saving or entering text does the same.

, : , ( : , ) .

, , , , ( SATA, SCSI, NFS...), ( ) , .

"", "", . "" .

, "" : , cout ( , , , ).

, , . "": , ( "" ).

(), " ", , , " -" ( )

, ( , ), . , .

+4

All Articles