Thursday, August 22, 2013

Matlab tic/toc functions in C++

For some applications (e.g. to test multithreading codes), it is extremely useful to have something like the Matlab tic/toc functions in you C++ program.

I will show you how to implement the tic() and toc() functions by using the ctime library.
Create a new header file (.h extension), called tic_toc.h with  the following content:

#ifndef TIC_TOC
#define TIC_TOC

#include <iostream>
#include <ctime>

// Just a static variable that will be visible only within this file

 static time_t start_time=time(0);

void tic()

void toc()
    time_t end_time=time(0);   
    std::cout<<"Elapsed time is "<<difftime(end_time, start_time)<<" seconds."<<std::endl;

#endif TIC_TOC

Now let's see an example on how to use this header file. Basically, the tic() and toc() functions must be within specific point in the main.
Excercise (a very simple one) how much time does it take to fill 1E8 entries into a vector of double?

Here is the code, stored in a file called test-tic_toc.cpp

/* ***  Testing tic toc *** */
#include "tic_toc.h"
#include <iostream>
#include <vector>

using namespace std;

int main()

  // Setting the time counter... tic();
 cout<<"Welcome to the test tic/toc program"<<endl;

 // Creating a vector of doubles (and size zero)    vector<double> v(0);
    for (int i=0; i<1E8; ++i)
        v.push_back(i); // fill the vector
    return 0;

That's it! Now...

On OSX and Linux, to compile and run the program, open a terminal, walk through the folder containing your code and type:

g++ -o a.out test-tic_toc.cpp; ./a.out

On my machine (Intel 2.66 GHZ Core 2 Duo from 2008), the output is:

Welcome to the test tic/toc program
Elapsed time is 3 seconds.

On Windows,  you should use VisualC++ Express and run the program from the prompt.

If something does not run, ASK YOURSELF:

1) Am I  in the correct folder?
2) Did I put the header file is in the same folder of my test-tic_toc.cpp file?

3) Do I have gcc on my machine?