What is the time complexity of making a cout <<
in C++?
If I have a cout
in a loop, for example:
for(int i = 0; i < 1000000 ;i++){
std::cout << i << endl;
}
Without the std::cout << i << endl;
would it be much faster the loop?
What is the time complexity of making a cout <<
in C++?
If I have a cout
in a loop, for example:
for(int i = 0; i < 1000000 ;i++){
std::cout << i << endl;
}
Without the std::cout << i << endl;
would it be much faster the loop?
Time complexity of C++ cout?
The time complexity of cout
is O(1). It can be bound by a constant and its not dependent on the data in your example. For a better estimate, we would need to see what is going on inside the insertion operator. For your example with the integer output, I'm guessing its the classic divide-then-ouput, so its O(1), too. The complexity does not increase as the number i
gets larger.
The time complexity of for(int i = 0; i < 1000000 ;i++)
is also O(1), but the constant is large at 1000000. The complexity does not grow with different sizes of data.
Combined, 1000000 · O(1) is still O(1).
Usually you don't want such a large constant. However, I have seen some algorithms where a constant of 1000000 was better than exponential growth. For example, I recall seeing an algorithm that ran in O(n3). 1000000 · O(n) is a "better deal" then O(n3) when n ≥ 1000 or so. Also see equation solver.
I hesitate to point you towards What is a plain English explanation of “Big O” notation?, but you may as well have a look. The accepted answer is wrong, and all the upvotes appear to be from folks who don't know the finer points of algorithm analysis. There are better answers in the question.
It appears to be a common mistake to use std::endl every time you want a new line. This is not necessarily wrong so much as it defeats the built in buffering in streams because it flushes the stream buffer each time that it is inserted onto the stream.
Time complextiy of Cout<<:
It completely depends on what type you are printing, how you overload your "operator<<", what operations you are doing inside "operator<< overloaded function.
ostream& operator<<(ostream& os, const "yourType"& T)
second question: Yes. Obviously. "Jon Trauntvein" provided good info on it.