c++ loop speed up

I wanted to test how clock function works so i made a simple program but i found something else.

#include <stdio.h>
#include <iostream>
#include <string>
#include <time.h>
#include <ctime>

using namespace std;

int main(){
clock_t start=clock();
for (int i=0;i<1000000;i++){
//printf("%d\n",i);
cout<<i<<"\n";
}
clock_t ende=clock();
double elapsed_secs = double(ende - start) / CLOCKS_PER_SEC;
printf("%f\n",elapsed_secs);
return 0;
}

Its same when i use printf, and my problem is that after its print numbers up to 10000 printing speed up like insanely speed up. I use mingw64 default for dev c++ .Why is that heppening?
I use g++ (linux).
Optimization option is -O3.
printf takes 79s.
cout takes 103s.
Approximately same.
What exaclty are you talking about?
Its same when i use printf, and my problem is that after its print numbers up to 10000 printing speed up like insanely speed up.

What?
I have this compiler options

g++ -O2 -std=c++14 -Wl,-stack -Wl,268435456

and i let i loop from 0 to 30000 and it takes about 45s but first 10000 numbers takes 2/3 of complete time (more then 30s ) and then it gets faster so the last 20000 numbers get printed 2 times faster then first 10000.
It looks like it's accelerating, but i have no idea why .
Last edited on
printing to the console is slow.
if you want it to go fast, run the executable redirected to a file :)

I had a co-worker dealing with this once, I took out all his pointless print statements and his program went from taking all night to run to taking like 30 min.


the computer / OS and hardware all have some caching and other tricks that can make something accelerate. It can be tricky to judge something in a tight loop that in reality would be called after or around other code, pushing it out of the cache or whatever... it matters a lot. There are also pipelines and such in play. Some cpu even change their speeds when hit with a load, then throttle back when idle, to save power.

there is another way to do it of course. This may or may not be faster. A single call to cout may be faster than a bunch of little calls. But that ITOA is expensive. Sprintf into a buffer or a smarter string function call might be faster also, not sure. Or a stringstream. I don't do text and am unsure which is fastest.

string s = "";
for (int i=0;i<1000000;i++)
{
s += itoa(i);
s+= "\n";
}
cout << s << endl;
Last edited on
Thanks for explanation. I actually didnt wanted to make a program for printing, just wanted to try using clock() but when i saw that acceleration i just wanted to know why. Thanks!
Topic archived. No new replies allowed.