C++显示程序执行的开始时间和结束时间



我必须为我的数据结构和算法类完成这项任务。我必须显示排序所需的执行时间。我设法显示了持续时间,但我的教授希望我显示开始时间和结束时间。

以下是我显示持续时间的片段请注意,大部分代码都被切断了。

#include <iostream>
#include <iomanip>
#include "stdafx.h"
#include <chrono>
using namespace std;
using namespace std::chrono;
int main()
// Starting time for the clock.
auto start = high_resolution_clock::now();
// Insert sorting function code here.
// Ending the time for the clock.
auto stop = high_resolution_clock::now();
// Getting the duration of how much time was passed.
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by insertion sort: " << duration.count() << " microseconds" << endl;

我确实提前为一些微不足道的事情道歉。我从来没有和时代打过交道等等。我可能还删除了代码运行的其他重要方面。

谢谢你的帮助,祝你今天过得愉快。

将起始点和结束点转换为epoch以来的时间,并将其转换为所需的持续时间:

#include <iostream>
#include <iomanip>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
int main() {
// Starting time for the clock
auto start = high_resolution_clock::now();
// Simulate doing work
this_thread::sleep_for(microseconds{1000});
// Ending time for the clock
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Start time: " << duration_cast<microseconds>(start.time_since_epoch()).count() << endl;
cout << "End time: " << duration_cast<microseconds>(stop.time_since_epoch()).count() << endl;
cout << "Time taken by insertion sort: " << duration.count() << " microseconds" << endl;
}

计时器之间有一个非常重要的区别。在虚拟环境中,机器可能会被挂起,这可能会改变时间测量,因此您需要特别小心。由于对于运行时间,您通常只想测量代码执行所花费的时间,而不是等待运行的时间。

-挂钟时间

"现在是什么时间?"问题的答案,永远不应该用于测量经过的时间。NTP,用户,夏令时可以在测量之间调整此时间

-刻度时间(稳定时间(

单调递增计数器,用于测量经过的时间。

std::chrono::high_resolution_clock有一个测试is_steady(),用于确定它是否对测量经过的时间有效。

要显示开始和结束时间,一种常见的模式是记录开始墙时间,以刻度测量经过的时间,将刻度转换为秒,然后添加到开始时间以查找结束时间。

你可以阅读这个问题来找到许多关于如何打印时间的答案:如何在C++中获得当前时间和日期?

最新更新