using gettimeofday
function from sys/time.h
header file, i use this class:
#include <cstdlib>
#include <sys/time.h>
class Timer
{
timeval timer[2];
public:
timeval start()
{
gettimeofday(&this->timer[0], NULL);
return this->timer[0];
}
timeval stop()
{
gettimeofday(&this->timer[1], NULL);
return this->timer[1];
}
int duration() const
{
int secs(this->timer[1].tv_sec - this->timer[0].tv_sec);
int usecs(this->timer[1].tv_usec - this->timer[0].tv_usec);
if(usecs < 0)
{
--secs;
usecs += 1000000;
}
return static_cast<int>(secs * 1000 + usecs / 1000.0 + 0.5);
}
};
for example:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
Timer tm;
std::ostringstream ooo;
std::string str;
tm.start();
for(int i = 0; i < 10000000; ++i)
{
ooo << "This is a string. ";
}
tm.stop();
std::cout << "std::ostingstream -> " << tm.duration() << std::endl;
tm.start();
for(int i = 0; i < 10000000; ++i)
{
str += "This is a string. ";
}
tm.stop();
std::cout << "std::string -> " << tm.duration() << std::endl;
}