Summary
I have this C++ code:
#include <iostream>
#include <chrono>
int main() {
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
for (int counter = 0; counter < 80000;) {
std::printf("%d\n", counter++);
}
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << std::endl << "Time difference (sec) = " << (std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.0 << std::endl;
std::cin.get();
return 0;
}
When running the code after compiling with g++ Source.cpp -O3
, the run time is usually around 25 seconds on my machine. However, if I use g++ Source2.cpp -std=c++14 -O3
for compiling, the run time I'm getting is more than 90 seconds.
More details
I am compiling with g++
version 8.2.0
which defines __cplusplus
to be 201402L
. Therefore, by default, it should be compiling under the C++14 standard.
It therefore seems strange that the code would run much slower when I add the -std=c++14
flag. I also noticed that the code runs just as slow if I use -std=c++11
, so it seems that just using -std=
is the problem.
NB 1: I use printf()
instead of cout
within the loop because I am aware that the former is faster.
NB 2: My question is totally different than Code running slower with g++ -std=c++0x, even though the title might sound similar.
Update
Based on suggestions in the comments, I tried to run the code with writing to a file instead of printing to the terminal. In that case, there was no significant difference in the run times.
I also ran the code in different terminals on Windows: cmd
, PowerShell
, cmder
. I found out that, while the exact run times are different on each terminal, the code without the -std=
flag still generally runs at least twice as fast.
(When running the program on the terminals, I made sure to start a new terminal before every run, in order to ensure that the terminal history does not impact the run time.)
So, the specific question is:
Why does adding the flag make the code run slower when the code prints to a terminal?
Update 2
After running more tests, I realized that the difference is negligible when using a terminal which prints out the code in a short amount of time (a few seconds or less than a second).
It seems that the difference in run times that I was getting is peculiar to the environment of my machine and may not be replicable.
Nevertheless, the insights provided by Michael in his answer and comments are valuable and might help explain problems of a similar nature faced by others.