matlab tic toc equivalent in C++

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.


You can look at the boost date_time module which might be more portable.


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

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;

Tags:

Time

C++

Timer