如何计算执行 C++ 程序所花费的时间,不包括用户输入所花费的时间?

How to calculate time taken to execute C++ program excluding time taken to user input?

我正在使用下面的代码来计算执行时间。当我从 ./a.out < input.txt 获取输入时效果很好。但是当我手动输入我的输入时,它也包括那个时间。有没有办法排除用户输入的时间?

  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";

编辑:我知道我们可以计算 cin 之前和之后的时间,然后减去它。还有其他办法吗?

一种直接的方法是在需要用户输入时“冻结时间”,因此不要在输入行之后创建 end 变量,而是在输入行之前创建它并在输入行之后重新开始时间计算输入:

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";