1

This question is in reference to this question of mine Time Difference between the execution of the C++ program with and without print statement.

Look at these codes:

1) Without print statement:

#include <iostream>
#include <ctime>
#include <boost/multiprecision/cpp_int.hpp>
using big_int = boost:: multiprecision:: cpp_int;
using namespace std;
clock_t start = clock();

int main() {
    for(big_int i = 0; i < 10000000; ++i) {
    }
    double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
    cout << endl << "Time is " << elapsedTime << " Seconds";
    return 0;
}

Execution Time:

Time is 0.370125 Seconds

2) With print statement

#include <iostream>
#include <ctime>
#include <boost/multiprecision/cpp_int.hpp>
using big_int = boost:: multiprecision:: cpp_int;
using namespace std;
clock_t start = clock();


int main() {
    for(big_int i = 0; i < 10000000; ++i) {
         cout << i << endl;
    }
    double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
    cout << endl << "Time is " << elapsedTime << " Seconds";
    return 0;
}

Execution Time:

Time is 26.8947 Seconds

I want to know that like these two codes why there is not a significant difference in the execution time of the codes mentioned in this question.

Community
  • 1
  • 1
Arun Suryan
  • 1,615
  • 1
  • 9
  • 27
  • a smart compiler can optimize out empty loops. and writing to `cout` takes a hit calling the system calls. – Daniel A. White Apr 07 '20 at 02:40
  • So, it is nothing to do with overhead related to the output buffer? – Arun Suryan Apr 07 '20 at 02:41
  • 1
    Are you asking this new question to get an answer for your other question? Why don't you edit that question to make it clearer. – Blastfurnace Apr 07 '20 at 02:42
  • 1
    Here you're comparing an empty loop and a loop that prints something. No work versus some work. Your other question compares a loop that does a lot of work and a loop that does the same work but adds a single print statement. Your time in other code is dominated by the computation, not the single additional print. – Blastfurnace Apr 07 '20 at 02:42
  • Because the previous question contains already large amount of code, So I thought it's better to ask a new to clarify – Arun Suryan Apr 07 '20 at 02:43
  • No, you need a single question, not another question seeking clarification for the previous question. – Blastfurnace Apr 07 '20 at 02:44
  • OK, @Blastfurnace I will take care of this in the future. – Arun Suryan Apr 07 '20 at 02:44

0 Answers0