alienCY
alienCY

Reputation: 225

Computing speed / make programs faster

I've run the following program which took my pc 94 seconds to execute (I have an i5 3.2 GHz cpu with 4 Gb ram) .

I think that 94 seconds for printing a million numbers is not fast. Is there a way to make it faster ?

Also why does the program end in 0.016 seconds when I don't cout my counter variable ? ( Does it really loop a million times in that time period of 0.016 seconds ? )

#include <iostream>

int main()
{
    for (int counter{1}; counter <= 1e6 ; ++counter)
{
    std::cout << counter << " ";
}

    return 0;
}

Upvotes: 0

Views: 270

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 62120

This question has nothing to do about "computing speed" nor about "making programs faster". Incrementing a counter hardly counts as computing, and the performance overhead of emitting text to a console (that is, invoking std::cout) overshadows the computational cost of incrementing a variable by several orders of magnitude.

So, this question is about the slowness of emitting text to a console.

Emitting text to a console is generally viewed as something that does not need to be terribly efficient, and for this reason it is kind of slow in most operating systems, under most scenarios. This is kind of an unfortunate situation, because software is generally emitting text to a console when we are developing it, so it slows down the development process, but it is not too bad, because software in production environments generally does not do that: the logs are written into text files, and this is considerably faster.

Also, keep in mind that the process of emitting text to a console involves auxiliary overhead factors such as scrolling: once your screen has filled up with text, every new line of text causes the console window to scroll. That's quite expensive, too.

So, wanna make your printing program run faster? Immediately after starting it, minimize the console window; then immediately restore it to its original dimensions; you will find that it will be done. Almost all of the overhead is in displaying text and scrolling the window.

Upvotes: 1

Related Questions