00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
#ifndef Timer_h
00029
#define Timer_h
00030
00031
#include <iostream>
00032
#include <stdio.h>
00033
#include <time.h>
00034
00035
#ifndef WIN32
00036
# include <sys/time.h>
00037
#endif
00038
00039
using namespace std;
00040
00042 class Timer {
00043
private:
00044
static long indent;
00045
00046
static double best;
00047
static double worst;
00048
static double total;
00049
static long count;
00050
00051
#ifdef WIN32
00052
long tc_start;
00053
#else
00054
struct timeval tv_start;
00055
#endif
00056
char* msg;
00057
bool summary;
00058
00059
public:
00060
inline Timer (
const bool summary=
false ) {
00061
Timer( (
char*)NULL, summary );
00062 }
00063
00064
inline Timer (
char* m,
const bool summary=
false ) {
00065
00066 ++Timer::indent;
00067 this->msg = m;
00068 this->summary = summary;
00069
reset();
00070 }
00071
00072
inline void reset ( ) {
00073
#ifdef WIN32
00074
this->tc_start = GetTickCount();
00075
#else
00076
00077
struct timezone tz_start;
00078 gettimeofday(&tv_start, &tz_start);
00079
#endif
00080
}
00081
00082
inline double getElapsedTime ( ) {
00083
#ifdef WIN32
00084
const long tc_end = GetTickCount();
00085
return ( (tc_end-this->tc_start)/1E3 );
00086
#else
00087
struct timeval tv_end;
00088
struct timezone tz_end;
00089 gettimeofday(&tv_end, &tz_end);
00090
const double d_start = tv_start.tv_sec + (tv_start.tv_usec / 1E6);
00091
const double d_end = tv_end.tv_sec + (tv_end.tv_usec / 1E6);
00092
return ( d_end-d_start );
00093
#endif
00094
}
00095
00096
inline void report ( ) {
00097
00098
00099
for (
int i=0; i<Timer::indent; i++) cout <<
" ";
00100
if (this->msg != NULL) {
00101 cout << this->msg <<
" time= " <<
getElapsedTime() <<
"s";
00102 }
else {
00103 cout <<
"time= " <<
getElapsedTime() <<
"s";
00104 }
00105
00106
if (this->summary) {
00107 cout <<
", best=" << Timer::best <<
", worst=" << Timer::worst
00108 <<
", average=" << (Timer::total/Timer::count);
00109 }
00110
00111 cout << endl;
00112 }
00113
00114
inline ~
Timer ( ) {
00115
const double t =
getElapsedTime();
00116
if (this->summary) {
00117 Timer::total += t;
00118 ++Timer::count;
00119
if (t>Timer::worst) Timer::worst=t;
00120
if (t<Timer::best) Timer::best =t;
00121 }
00122
report();
00123 --Timer::indent;
00124 }
00125 };
00126
00127
long Timer::indent = 0;
00128
double Timer::best = FLT_MAX;
00129
double Timer::worst = 0.0;
00130
double Timer::total = 0.0;
00131
long Timer::count = 0;
00132
00133
#endif
00134
00135