Mittwoch, 7. November 2012

Measuring time in C++

inline double startTime() {
  struct timeval tp;
  double sec, usec;
  // Time stamp before the computations
  gettimeofday(&tp, NULL);
  sec = static_cast(tp.tv_sec);
  usec = static_cast(tp.tv_usec) / 1E6;
  return sec + usec;
}

inline double elapsedTime(double starttime) {
  struct timeval tp;
  double sec, usec;
  // Time stamp after the computations
  gettimeofday(&tp, NULL);
  sec = static_cast(tp.tv_sec);
  usec = static_cast(tp.tv_usec) / 1E6;
  // Time calculation (in seconds)
  return sec + usec - starttime;
}
A relatively easy way to measure time in C++ is to use standard linux libraries:
#include <sys/time.h>
#include <sys/types.h>
The first function (that can e.g. be global) returns the system time as double in microseconds. The second one computes the elapsed time according to the measurement given by the first function.
Application example:
...
double start = startTime();
// do something time consuming...
double elapsed = elapsedTime(start);
cout << "The operation took " << elapsed << "µs" << endl;
...

Keine Kommentare:

Kommentar veröffentlichen