1

For example.. if I had.

#include <iostream>
using namespace std;

int main()
{
   int counter = 0;
   while (true)
   {
      cout << counter << endl;
      counter++
   }
}

And say I was on a race to counting to 1 billion against other computers, is the rate at which this loop runs purely dependent on the computer processor speed? Or is there a limit on how fast my program can run, which could be changeable?

Theodoros Chatzigiannakis
  • 27,825
  • 8
  • 68
  • 102
Tommy Saechao
  • 1,061
  • 3
  • 15
  • 26

4 Answers4

12

Get rid of the endl and use "\n" instead. Plan on at least a 4x speed up from that alone.

Write the output to a file instead of the screen. That should be good for another 10x speed improvement (or so--more if you use an SSD).

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
2

Use printf from <cstdio>, it's a good bit faster than cout.

printf("%d\n", counter);
Andy M
  • 576
  • 3
  • 7
2

If you are using cout but NOT using anything from the library <cstdio>, you can write this in the beginning of the int main() function:

    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
0

The slowness of your posted program comes from formatting internal representation to a human readable form (textual representation) and outputting the textual representation.

One optimization not mentioned is to buffer your formatted output, then ouput it. For example, write the formatted text to a buffer, then every 100 or so counts, print out the buffer using a block write. The objective is to reduce the number of output transactions and to make each transaction have a larger amount of data. Basically, one output of 1024 characters will be faster than 1024 outputs of 1 character.

The output depends on the OS and other factors that are beyond your program's control. Your program send the data, for output, to the OS and waits for the OS to complete the request. The completion time depends on task priorities and resource availability (at least). So if your program can count in milliseconds but the I/O takes seconds, your out of luck as no program optimization will help.

Thomas Matthews
  • 54,980
  • 14
  • 94
  • 148
  • 1
    You do realize that an iostream uses a streambuf, which normally does buffering, about like you've described? (Oh, but at least most compilers I've used recently use a larger buffer than you've described, so your method would probably slow it down). – Jerry Coffin Nov 06 '15 at 00:20
  • Yes, I'm aware of the stream buffer, but I like the old fashioned control method. Also, there is the overhead of each call to the output and reducing the quantity of calls reduces the overhead, saving time. – Thomas Matthews Nov 06 '15 at 00:44