Reputation: 789
I have searched but I can't find an equivalent to the matlab tic/toc function to simply display on the console how long time took the program to do its processing. (ideally I would like to put the tic (start timer) and toc (end timer) anywhere in the program.
Any suggestions?
Upvotes: 15
Views: 27550
Reputation: 101
By using std::chrono
you can write a simple function that performs as Matlab's tic toc:
#include <iostream>
#include <chrono>
#include <thread> // sleep_for, for testing only
void tic(int mode=0) {
static std::chrono::_V2::system_clock::time_point t_start;
if (mode==0)
t_start = std::chrono::high_resolution_clock::now();
else {
auto t_end = std::chrono::high_resolution_clock::now();
std::cout << "Elapsed time is " << (t_end-t_start).count()*1E-9 << " seconds\n";
}
}
void toc() { tic(1); }
int main(int argc, char **argv)
{
tic();
// wait 5 seconds just for testing
std::chrono::seconds sleep_s(5);
std::this_thread::sleep_for(sleep_s);
toc();
return 0;
}
Upvotes: 4
Reputation: 789
I found what I was looking for. Include:
#include <ctime>
Then at the beginning:
time_t tstart, tend;
tstart = time(0);
And finally before the end:
tend = time(0);
cout << "It took "<< difftime(tend, tstart) <<" second(s)."<< endl;
Upvotes: 25
Reputation: 87376
You can look at the boost date_time module which might be more portable.
Upvotes: 3
Reputation: 21351
If you are on linux you can use the function
clock_gettime();
if on windows try
QueryPerformanceCounter()
You can google these for specific implementation details. Other operating systems I dont know about. There are doubtless many other ways to achieve the same thing but if you get no other responses, these are a reasonable place to start.
Upvotes: 2