The following complete program shows how this can be done, by using the std::chrono
facilities added in C++11:
#include <iostream>
#include <chrono>
#include <thread>
int main(int argc, char *argv[]) {
// Check args.
if (argc != 2) {
std::cerr << "Usage: testprog <sleepTime>" << std::endl;
return 1;
}
// Create a millisecond sleep time from argument.
auto sleepTime = strtoul(argv[1], nullptr, 10);
sleepTime = sleepTime * 1234 + 1000;
std::cout << "Given '" << argv[1] <<
"', should sleep for about " << sleepTime <<
"ms ... " << std::flush;
// Get the start time, then wait for a bit.
auto startTime(std::chrono::high_resolution_clock::now());
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
// Get end time, work out and print duration.
auto endTime(std::chrono::high_resolution_clock::now());
auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
(endTime - startTime));
std::cout << "that took " << duration.count() << "ms." << std::endl;
}
Running this with the following bash
test command:
for i in {0..10} ; do ./testprog $i ; done
gives you the results you would expect:
Given '0', should sleep for about 1000ms ... that took 1000ms.
Given '1', should sleep for about 2234ms ... that took 2235ms.
Given '2', should sleep for about 3468ms ... that took 3469ms.
Given '3', should sleep for about 4702ms ... that took 4703ms.
Given '4', should sleep for about 5936ms ... that took 5937ms.
Given '5', should sleep for about 7170ms ... that took 7170ms.
Given '6', should sleep for about 8404ms ... that took 8404ms.
Given '7', should sleep for about 9638ms ... that took 9638ms.
Given '8', should sleep for about 10872ms ... that took 10872ms.
Given '9', should sleep for about 12106ms ... that took 12106ms.
Given '10', should sleep for about 13340ms ... that took 13340ms.
The important lines in that code are really just the ones that get the start and end time-points then work out the duration between them. They can be boiled down to:
#include <chrono>
auto startTime(std::chrono::high_resolution_clock::now());
// Do whatever you want to time.
auto endTime(std::chrono::high_resolution_clock::now());
auto duration(std::chrono::duration_cast<std::chrono::milliseconds>
(endTime - startTime));
auto elapsedMs = duration.count();
#include <chrono>
is the right place to start. Take a look atstd::chrono::high_resolution_clock
cin
andprintf
in the same code? That's just Jekyll and Hyde stuff and, yes,printf
is the Hyde bit :-)