I have implemented a C++ code on a Zedboard. It compiles and runs perfectly, but now i would like to check the performances in order to optimize some functions. I have chec
You can create a simple timer class using the <chrono>
header. Something like this:
class Timer
{
public:
using clock = std::chrono::steady_clock;
void clear() { start(); tse = tsb; }
void start() { tsb = clock::now(); }
void stop() { tse = clock::now(); }
auto nsecs() const
{
using namespace std::chrono;
return duration_cast<nanoseconds>(tse - tsb).count();
}
double usecs() const { return double(nsecs()) / 1000.0; }
double msecs() const { return double(nsecs()) / 1000000.0; }
double secs() const { return double(nsecs()) / 1000000000.0; }
friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
{
return o << timer.secs();
}
private:
clock::time_point tsb;
clock::time_point tse;
};
You can use it simply like this:
Timer timer;
timer.start();
// do some stuff
std::this_thread::sleep_for(std::chrono::milliseconds(600));
timer.stop();
std::cout << timer << " seconds" << '\n';
EDIT: On POSIX
systems you can use clock_gettime()
if <chrono>
is not available:
class Timer
{
public:
void clear() { start(); tse = tsb; }
void start() { clock_gettime(CLOCK_MONOTONIC, &tsb); }
void stop() { clock_gettime(CLOCK_MONOTONIC, &tse); }
long nsecs() const
{
long b = (tsb.tv_sec * 1000000000) + tsb.tv_nsec;
long e = (tse.tv_sec * 1000000000) + tse.tv_nsec;
return e - b;
}
double usecs() const { return double(nsecs()) / 1000.0; }
double msecs() const { return double(nsecs()) / 1000000.0; }
double secs() const { return double(nsecs()) / 1000000000.0; }
friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
{
return o << timer.secs();
}
private:
timespec tsb;
timespec tse;
};
I have found an unsatisfying solution, but I thought I could still post it if it can be of any help.
I made use of the gettimeofday()
function defined in <time.h>
. It's pretty simple to use but has flaws which i may explain later :
timeval t1, t2;
gettimeofday(&t1, NULL);
/* some function */
gettimeofday(&t2, NULL);
double time;
time = (t2.tv_sec - t1.tv_sec)*1000.0 + (t2.tv_usec - t1.tv_usec)/1000.0;
cout << time << "ms" << "\n";
This way I measure a time in milliseconds and display it on screen. However gettimeofday
is not based on the computer clock but on the actual time. To be clear, the time elapsed between 2 calls contains indeed my function, but also all the processes running in the background on Ubuntu. In other terms, this does not give me the precise time taken by my function to execute, but a value slightly higher.
EDIT : I found another solution again, using the clock()
function from <time.h>
and the result seems correct in comparison of the ones i get with the previous method. Unfortunately, the precision is not enough since it gives a number in seconds with only 3 digits.