Code Profiling for time in C++

Code profiling is a very important aspect of programming. First you must be wondering what is code profiling. You can always google it but in simple words “code profiling” is just measuring of the resources used by your program or small sections of your program.

Here I will be talking about code profiling for “time”. Dynamically measuring your code for how much time it takes for different input sets is of keen importance when you have to optimise your code. There are many ways you can achieve this,

  • there are many unix tools available to do the job for you.
    • time – just type time while calling your executable file.
      eg: time ./a.out
    • sysstat (to install just type “sudo apt-get install sysstat”) – It has many tools available to check the resources used up in the running processes.
      While your program is running, you can check up the resources used up your program by the commands “iostat -i”, “iostat -c”, “iostat -dx”. if networking is involved you can use “netstat -i”, “netstat -s”. To check the memory usage, i.e., free memory and used memory and memory swapped etc., you can type “free -m”.
    • callgrind – you can download this tool to profile your code.
  • The simple way is to put a small code inside your code to measure the time. Here I’ll tell you how to do that using a small library I have written.

 Its use as simple as writing:

int func() {
    timeit s(“func()”);
    // your code here.
}

It is based on a simple concept that when a object goes out of its scope, its destructor is called. So to time a code snippet, you just have to make an object of the type “timeit” having the same scope as the code snippet. In the above example it will print to the standard error:
     
           func()       3.21554ms

 The object simply times the call between its construction and destruction. If its difficult to maintain the scope of the object by using curly brackets, then you can also use the “new” and “delete” to manually set the scope. The code is rather simple and here it goes:

#include <iostream>
#include <ctime>

class timeit {
    char const *name;
    timespec t_start;

    public:
        
        timeit(char const *temp): name(temp) {
            clock_gettime(CLOCK_REALTIME, &t_start);
        }
        
        ~timeit() {
            timespec t_end;
            clock_gettime(CLOCK_REALTIME, &t_end);
            
            double dur = 1e3 * (t_end.tv_sec - t_start.tv_sec) + 1e-6 * (t_end.tv_nsec - t_start.tv_nsec);
            std::cerr << name << '\t' << std::fixed << dur << " ms\n";
        }
};

Just include this this code in your program and timeit 😉