Sometimes is quite interesting to measure the run time of a given snippet your code. In C++11 is very simple and in my case I’m using just like that.
In my .h file I define
#ifndef __PROFILER__H #define __PROFILER__H #include <chrono> using namespace std::chrono; high_resolution_clock::time_point start(void); high_resolution_clock::time_point end(void); void finished(high_resolution_clock::time_point, high_resolution_clock::time_point); #endif
And in my .cpp file
#include <iostream>
#include "profiler.h"
high_resolution_clock::time_point start(void)
{
return high_resolution_clock::now();
}
high_resolution_clock::time_point end(void)
{
return high_resolution_clock::now();
}
void finished(high_resolution_clock::time_point start, high_resolution_clock::time_point end)
{
duration<double> elapse = end - start;
std::cout << "Elapsed time for function " << __FUNCTION__ << " :"<< elapse.count() << "s" << std::endl;
}
In order to use the code you just need to add the code ‘surrounded’ by start and finished functions, passing end as parameter. Like that:
#include <iostream>
// It's not often that you'll profiling your code so just add a D flag
// See Makefile
#if PROFILER
#include "profiler.h"
#endif
// Some function to measure
void initLoad(void) {
cout << "Initializing data in memory..." << endl;
#if PROFILER
high_resolution_clock::time_point s = start();
#endif
for (int i = 0; i < 100000000000; i++)
cout << i << endl;
#if PROFILER
finished(s, end());
#endif
}
In your Makefile you can use a D flag to optionally compile your code to use the profiling, such as:
SRC = $(wildcard src/*.cpp) PROG_NAME = test INCLUDE = -Iinclude LIBS = -Ilibs FLAGS = -std=c++0x DFLAGS = -q -nx -tui PROFILER ?= 0 # To use profiler just add: make PROFILER=1 ifeq ($(PROFILER), 1) FLAGS += -DPROFILER endif test: g++ -o $(PROG_NAME) $(SRC) $(INCLUDE) $(LIBS) $(FLAGS)
Now you can use this ‘lib’ for any source you want to measure the run time typing: make PROFILER=1 🙂
That’s all folks!
