Home > Net >  How to calculate time taken to execute C program excluding time taken to user input?
How to calculate time taken to execute C program excluding time taken to user input?

Time:05-19

I'm using the below code to calculate the time for execution. It works well when I take input from ./a.out < input.txt. But when I manually write my input it also includes that time. Is there a way to exclude the time taken by the user to input?

  auto begin = chrono::high_resolution_clock::now();

  // my code here has cin for input

  auto end = chrono::high_resolution_clock::now();
  cout << chrono::duration_cast<chrono::duration<double>>(end - begin).count() << " seconds";

Edit: I know that we can count the time before cin and after then subtract it. Is there any other way?

CodePudding user response:

A straightforward approach would be to "Freeze time" when user input is required, so instead of creating the end variable after the input lines, create it before the input lines and restart time calculation again after the input:

double total = 0;

auto begin = chrono::high_resolution_clock::now();
// code that needs time calculation
auto end = chrono::high_resolution_clock::now();
total  = chrono::duration_cast<chrono::duration<double>>(end - begin).count();

// your code here that has cin for input

begin = chrono::high_resolution_clock::now();
// code that needs time calculation
end = chrono::high_resolution_clock::now();
total  = chrono::duration_cast<chrono::duration<double>>(end - begin).count();

cout << total << " seconds";
  • Related