Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for benchmarking code snippet (c++)

Tags:

Some loading routines in my program takes to long to complete. I want a quick small snippet for checking how long a function took to execute. By small I mean "preferably without 3rd party libraries".

Maybe something as simple as taking the system time?

start = current_system_time()
load_something()
delta = current_system_time()-start
log_debug("load took "+delta)

Edit: Target OS in question is Windows.

like image 618
Mizipzor Avatar asked Jan 27 '09 12:01

Mizipzor


3 Answers

Your answer: Yes

Caveat: That WON'T work in multihtreaded code or multiple core machines, you need a robust wall-clock timer. So I recommend you use omp's wallclock. OMP is included with VC and GCC, and most compilers and its a standard you don't need to worry about disappearing

#include <omp.h>

// Starting the time measurement
double start = omp_get_wtime();
// Computations to be measured
...
// Measuring the elapsed time
double end = omp_get_wtime();
// Time calculation (in seconds)
like image 116
Robert Gould Avatar answered Oct 01 '22 01:10

Robert Gould


#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)

namespace win32 {
    #include <windows.h>
}

class timer
{
    win32::LARGE_INTEGER start_time_;
public:
    timer() { QueryPerformanceCounter( &start_time_ ); }
    void   restart() { QueryPerformanceCounter( &start_time_ ); }
    double elapsed() const
    {
        win32::LARGE_INTEGER end_time, frequency;
        QueryPerformanceCounter( &end_time );
        QueryPerformanceFrequency( &frequency );
        return double( end_time.QuadPart - start_time_.QuadPart )
            / frequency.QuadPart;
    }
};

#else

#include <ctime>

class timer
{
    clock_t _start_time;
public:
    timer() { _start_time = clock(); }
    void   restart() { _start_time = clock(); }
    double elapsed() const
    {
        return double(clock() - _start_time) / CLOCKS_PER_SEC;
    }
};

#endif

template< typename Func >
double measure_time( Func f )
{
    timer t;
    f();
    return t.elapsed();
}
like image 31
Vadim Ferderer Avatar answered Oct 01 '22 02:10

Vadim Ferderer


This is a quick and dirty way to time a block of C/C++ code. You need to #include <sys/time.h>, which should be a standard header...

struct timeval start, end;
gettimeofday(&start, NULL);
// benchmark code
gettimeofday(&end, NULL);
long long time =   (end.tv_sec * (unsigned int)1e6 +   end.tv_usec) - 
                 (start.tv_sec * (unsigned int)1e6 + start.tv_usec);

This should give 1-2µs resolution on modern Linux systems (what OS are you using?), which means that it's not well suited to learning much for items taking of <10µs. However, you don't seem to be in that situation.

Update: Based on specified OS... Windows implementation of gettimeofday()

like image 33
jvasak Avatar answered Oct 01 '22 01:10

jvasak