Reputation: 13
I have this assignment I have to do for my data structures and algorithms class. I have to display the execution times for how long my sorts take. I managed to display the duration but my professor wants me to display the start time and end time.
Here is a snippet of me displaying the duration. Note that a majority of the code is cut off.
#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;
I do apologize in advance for something that could be so trivial. I have never worked with times and so forth. I also may have taken out other important aspects for the code to run as well.
Thank you for all the help and have a great day.
Upvotes: 0
Views: 3174
Reputation: 379
There is a very important distinction between timers. You need to be especially careful in virtual environments where the machine can be suspended which could alter time measurements. Since for elapsed time, you often want to only measure the time that your code took to execute not the time it was waiting to be run.
The answer to the question "What time is it?" and should never be used for measuring elapsed time. NTP, the User, daylight savings can adjust this time between your measurements
Monotonically increasing counter used for measuring elapsed time.
std::chrono::high_resolution_clock
has a test, is_steady()
, to determine if it is valid for measuring elapsed time.
To show start and end times a common pattern is to record the starting wall time, measure elapsed time in ticks, convert the ticks to seconds and add to the start time to find the end time.
You can read this question to find many answers on how to print out time: How to get current time and date in C++?
Upvotes: 1
Reputation: 881
Convert the start and end points to time-since-epoch, and cast them to the desired duration:
#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;
}
Upvotes: 2