lemon/time_measure.h
author Alpar Juttner <alpar@cs.elte.hu>
Tue, 10 Feb 2009 17:21:26 +0000
changeset 366 daddd623ac9a
parent 364 55111a054b2e
child 368 879c55700cd4
permissions -rw-r--r--
Set the compatibily related MSVC defines only if they has't been defined yet
     1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library.
     4  *
     5  * Copyright (C) 2003-2008
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     9  * Permission to use, modify and distribute this software is granted
    10  * provided that this copyright notice appears in all copies. For
    11  * precise terms see the accompanying LICENSE file.
    12  *
    13  * This software is provided "AS IS" with no warranty of any kind,
    14  * express or implied, and with no claim as to its suitability for any
    15  * purpose.
    16  *
    17  */
    18 
    19 #ifndef LEMON_TIME_MEASURE_H
    20 #define LEMON_TIME_MEASURE_H
    21 
    22 ///\ingroup timecount
    23 ///\file
    24 ///\brief Tools for measuring cpu usage
    25 
    26 #ifdef WIN32
    27 #ifndef WIN32_LEAN_AND_MEAN
    28 #define WIN32_LEAN_AND_MEAN
    29 #endif
    30 #ifndef NOMINMAX
    31 #define NOMINMAX
    32 #endif
    33 #include <windows.h>
    34 #include <cmath>
    35 #else
    36 #include <unistd.h>
    37 #include <sys/times.h>
    38 #include <sys/time.h>
    39 #endif
    40 
    41 #include <string>
    42 #include <fstream>
    43 #include <iostream>
    44 
    45 namespace lemon {
    46 
    47   /// \addtogroup timecount
    48   /// @{
    49 
    50   /// A class to store (cpu)time instances.
    51 
    52   /// This class stores five time values.
    53   /// - a real time
    54   /// - a user cpu time
    55   /// - a system cpu time
    56   /// - a user cpu time of children
    57   /// - a system cpu time of children
    58   ///
    59   /// TimeStamp's can be added to or substracted from each other and
    60   /// they can be pushed to a stream.
    61   ///
    62   /// In most cases, perhaps the \ref Timer or the \ref TimeReport
    63   /// class is what you want to use instead.
    64 
    65   class TimeStamp
    66   {
    67     double utime;
    68     double stime;
    69     double cutime;
    70     double cstime;
    71     double rtime;
    72 
    73     void _reset() {
    74       utime = stime = cutime = cstime = rtime = 0;
    75     }
    76 
    77   public:
    78 
    79     ///Read the current time values of the process
    80     void stamp()
    81     {
    82 #ifndef WIN32
    83       timeval tv;
    84       gettimeofday(&tv, 0);
    85       rtime=tv.tv_sec+double(tv.tv_usec)/1e6;
    86 
    87       tms ts;
    88       double tck=sysconf(_SC_CLK_TCK);
    89       times(&ts);
    90       utime=ts.tms_utime/tck;
    91       stime=ts.tms_stime/tck;
    92       cutime=ts.tms_cutime/tck;
    93       cstime=ts.tms_cstime/tck;
    94 #else
    95       static const double ch = 4294967296.0e-7;
    96       static const double cl = 1.0e-7;
    97 
    98       FILETIME system;
    99       GetSystemTimeAsFileTime(&system);
   100       rtime = ch * system.dwHighDateTime + cl * system.dwLowDateTime;
   101 
   102       FILETIME create, exit, kernel, user;
   103       if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
   104         utime = ch * user.dwHighDateTime + cl * user.dwLowDateTime;
   105         stime = ch * kernel.dwHighDateTime + cl * kernel.dwLowDateTime;
   106         cutime = 0;
   107         cstime = 0;
   108       } else {
   109         rtime = 0;
   110         utime = 0;
   111         stime = 0;
   112         cutime = 0;
   113         cstime = 0;
   114       }
   115 #endif
   116     }
   117 
   118     /// Constructor initializing with zero
   119     TimeStamp()
   120     { _reset(); }
   121     ///Constructor initializing with the current time values of the process
   122     TimeStamp(void *) { stamp();}
   123 
   124     ///Set every time value to zero
   125     TimeStamp &reset() {_reset();return *this;}
   126 
   127     ///\e
   128     TimeStamp &operator+=(const TimeStamp &b)
   129     {
   130       utime+=b.utime;
   131       stime+=b.stime;
   132       cutime+=b.cutime;
   133       cstime+=b.cstime;
   134       rtime+=b.rtime;
   135       return *this;
   136     }
   137     ///\e
   138     TimeStamp operator+(const TimeStamp &b) const
   139     {
   140       TimeStamp t(*this);
   141       return t+=b;
   142     }
   143     ///\e
   144     TimeStamp &operator-=(const TimeStamp &b)
   145     {
   146       utime-=b.utime;
   147       stime-=b.stime;
   148       cutime-=b.cutime;
   149       cstime-=b.cstime;
   150       rtime-=b.rtime;
   151       return *this;
   152     }
   153     ///\e
   154     TimeStamp operator-(const TimeStamp &b) const
   155     {
   156       TimeStamp t(*this);
   157       return t-=b;
   158     }
   159     ///\e
   160     TimeStamp &operator*=(double b)
   161     {
   162       utime*=b;
   163       stime*=b;
   164       cutime*=b;
   165       cstime*=b;
   166       rtime*=b;
   167       return *this;
   168     }
   169     ///\e
   170     TimeStamp operator*(double b) const
   171     {
   172       TimeStamp t(*this);
   173       return t*=b;
   174     }
   175     friend TimeStamp operator*(double b,const TimeStamp &t);
   176     ///\e
   177     TimeStamp &operator/=(double b)
   178     {
   179       utime/=b;
   180       stime/=b;
   181       cutime/=b;
   182       cstime/=b;
   183       rtime/=b;
   184       return *this;
   185     }
   186     ///\e
   187     TimeStamp operator/(double b) const
   188     {
   189       TimeStamp t(*this);
   190       return t/=b;
   191     }
   192     ///The time ellapsed since the last call of stamp()
   193     TimeStamp ellapsed() const
   194     {
   195       TimeStamp t(NULL);
   196       return t-*this;
   197     }
   198 
   199     friend std::ostream& operator<<(std::ostream& os,const TimeStamp &t);
   200 
   201     ///Gives back the user time of the process
   202     double userTime() const
   203     {
   204       return utime;
   205     }
   206     ///Gives back the system time of the process
   207     double systemTime() const
   208     {
   209       return stime;
   210     }
   211     ///Gives back the user time of the process' children
   212 
   213     ///\note On <tt>WIN32</tt> platform this value is not calculated.
   214     ///
   215     double cUserTime() const
   216     {
   217       return cutime;
   218     }
   219     ///Gives back the user time of the process' children
   220 
   221     ///\note On <tt>WIN32</tt> platform this value is not calculated.
   222     ///
   223     double cSystemTime() const
   224     {
   225       return cstime;
   226     }
   227     ///Gives back the real time
   228     double realTime() const {return rtime;}
   229   };
   230 
   231   TimeStamp operator*(double b,const TimeStamp &t)
   232   {
   233     return t*b;
   234   }
   235 
   236   ///Prints the time counters
   237 
   238   ///Prints the time counters in the following form:
   239   ///
   240   /// <tt>u: XX.XXs s: XX.XXs cu: XX.XXs cs: XX.XXs real: XX.XXs</tt>
   241   ///
   242   /// where the values are the
   243   /// \li \c u: user cpu time,
   244   /// \li \c s: system cpu time,
   245   /// \li \c cu: user cpu time of children,
   246   /// \li \c cs: system cpu time of children,
   247   /// \li \c real: real time.
   248   /// \relates TimeStamp
   249   /// \note On <tt>WIN32</tt> platform the cummulative values are not
   250   /// calculated.
   251   inline std::ostream& operator<<(std::ostream& os,const TimeStamp &t)
   252   {
   253     os << "u: " << t.userTime() <<
   254       "s, s: " << t.systemTime() <<
   255       "s, cu: " << t.cUserTime() <<
   256       "s, cs: " << t.cSystemTime() <<
   257       "s, real: " << t.realTime() << "s";
   258     return os;
   259   }
   260 
   261   ///Class for measuring the cpu time and real time usage of the process
   262 
   263   ///Class for measuring the cpu time and real time usage of the process.
   264   ///It is quite easy-to-use, here is a short example.
   265   ///\code
   266   /// #include<lemon/time_measure.h>
   267   /// #include<iostream>
   268   ///
   269   /// int main()
   270   /// {
   271   ///
   272   ///   ...
   273   ///
   274   ///   Timer t;
   275   ///   doSomething();
   276   ///   std::cout << t << '\n';
   277   ///   t.restart();
   278   ///   doSomethingElse();
   279   ///   std::cout << t << '\n';
   280   ///
   281   ///   ...
   282   ///
   283   /// }
   284   ///\endcode
   285   ///
   286   ///The \ref Timer can also be \ref stop() "stopped" and
   287   ///\ref start() "started" again, so it is possible to compute collected
   288   ///running times.
   289   ///
   290   ///\warning Depending on the operation system and its actual configuration
   291   ///the time counters have a certain (10ms on a typical Linux system)
   292   ///granularity.
   293   ///Therefore this tool is not appropriate to measure very short times.
   294   ///Also, if you start and stop the timer very frequently, it could lead to
   295   ///distorted results.
   296   ///
   297   ///\note If you want to measure the running time of the execution of a certain
   298   ///function, consider the usage of \ref TimeReport instead.
   299   ///
   300   ///\sa TimeReport
   301   class Timer
   302   {
   303     int _running; //Timer is running iff _running>0; (_running>=0 always holds)
   304     TimeStamp start_time; //This is the relativ start-time if the timer
   305                           //is _running, the collected _running time otherwise.
   306 
   307     void _reset() {if(_running) start_time.stamp(); else start_time.reset();}
   308 
   309   public:
   310     ///Constructor.
   311 
   312     ///\param run indicates whether or not the timer starts immediately.
   313     ///
   314     Timer(bool run=true) :_running(run) {_reset();}
   315 
   316     ///\name Control the state of the timer
   317     ///Basically a Timer can be either running or stopped,
   318     ///but it provides a bit finer control on the execution.
   319     ///The \ref lemon::Timer "Timer" also counts the number of
   320     ///\ref lemon::Timer::start() "start()" executions, and it stops
   321     ///only after the same amount (or more) \ref lemon::Timer::stop()
   322     ///"stop()"s. This can be useful e.g. to compute the running time
   323     ///of recursive functions.
   324 
   325     ///@{
   326 
   327     ///Reset and stop the time counters
   328 
   329     ///This function resets and stops the time counters
   330     ///\sa restart()
   331     void reset()
   332     {
   333       _running=0;
   334       _reset();
   335     }
   336 
   337     ///Start the time counters
   338 
   339     ///This function starts the time counters.
   340     ///
   341     ///If the timer is started more than ones, it will remain running
   342     ///until the same amount of \ref stop() is called.
   343     ///\sa stop()
   344     void start()
   345     {
   346       if(_running) _running++;
   347       else {
   348         _running=1;
   349         TimeStamp t;
   350         t.stamp();
   351         start_time=t-start_time;
   352       }
   353     }
   354 
   355 
   356     ///Stop the time counters
   357 
   358     ///This function stops the time counters. If start() was executed more than
   359     ///once, then the same number of stop() execution is necessary the really
   360     ///stop the timer.
   361     ///
   362     ///\sa halt()
   363     ///\sa start()
   364     ///\sa restart()
   365     ///\sa reset()
   366 
   367     void stop()
   368     {
   369       if(_running && !--_running) {
   370         TimeStamp t;
   371         t.stamp();
   372         start_time=t-start_time;
   373       }
   374     }
   375 
   376     ///Halt (i.e stop immediately) the time counters
   377 
   378     ///This function stops immediately the time counters, i.e. <tt>t.halt()</tt>
   379     ///is a faster
   380     ///equivalent of the following.
   381     ///\code
   382     ///  while(t.running()) t.stop()
   383     ///\endcode
   384     ///
   385     ///
   386     ///\sa stop()
   387     ///\sa restart()
   388     ///\sa reset()
   389 
   390     void halt()
   391     {
   392       if(_running) {
   393         _running=0;
   394         TimeStamp t;
   395         t.stamp();
   396         start_time=t-start_time;
   397       }
   398     }
   399 
   400     ///Returns the running state of the timer
   401 
   402     ///This function returns the number of stop() exections that is
   403     ///necessary to really stop the timer.
   404     ///For example the timer
   405     ///is running if and only if the return value is \c true
   406     ///(i.e. greater than
   407     ///zero).
   408     int running()  { return _running; }
   409 
   410 
   411     ///Restart the time counters
   412 
   413     ///This function is a shorthand for
   414     ///a reset() and a start() calls.
   415     ///
   416     void restart()
   417     {
   418       reset();
   419       start();
   420     }
   421 
   422     ///@}
   423 
   424     ///\name Query Functions for the ellapsed time
   425 
   426     ///@{
   427 
   428     ///Gives back the ellapsed user time of the process
   429     double userTime() const
   430     {
   431       return operator TimeStamp().userTime();
   432     }
   433     ///Gives back the ellapsed system time of the process
   434     double systemTime() const
   435     {
   436       return operator TimeStamp().systemTime();
   437     }
   438     ///Gives back the ellapsed user time of the process' children
   439 
   440     ///\note On <tt>WIN32</tt> platform this value is not calculated.
   441     ///
   442     double cUserTime() const
   443     {
   444       return operator TimeStamp().cUserTime();
   445     }
   446     ///Gives back the ellapsed user time of the process' children
   447 
   448     ///\note On <tt>WIN32</tt> platform this value is not calculated.
   449     ///
   450     double cSystemTime() const
   451     {
   452       return operator TimeStamp().cSystemTime();
   453     }
   454     ///Gives back the ellapsed real time
   455     double realTime() const
   456     {
   457       return operator TimeStamp().realTime();
   458     }
   459     ///Computes the ellapsed time
   460 
   461     ///This conversion computes the ellapsed time, therefore you can print
   462     ///the ellapsed time like this.
   463     ///\code
   464     ///  Timer t;
   465     ///  doSomething();
   466     ///  std::cout << t << '\n';
   467     ///\endcode
   468     operator TimeStamp () const
   469     {
   470       TimeStamp t;
   471       t.stamp();
   472       return _running?t-start_time:start_time;
   473     }
   474 
   475 
   476     ///@}
   477   };
   478 
   479   ///Same as Timer but prints a report on destruction.
   480 
   481   ///Same as \ref Timer but prints a report on destruction.
   482   ///This example shows its usage.
   483   ///\code
   484   ///  void myAlg(ListGraph &g,int n)
   485   ///  {
   486   ///    TimeReport tr("Running time of myAlg: ");
   487   ///    ... //Here comes the algorithm
   488   ///  }
   489   ///\endcode
   490   ///
   491   ///\sa Timer
   492   ///\sa NoTimeReport
   493   class TimeReport : public Timer
   494   {
   495     std::string _title;
   496     std::ostream &_os;
   497   public:
   498     ///Constructor
   499 
   500     ///Constructor.
   501     ///\param title This text will be printed before the ellapsed time.
   502     ///\param os The stream to print the report to.
   503     ///\param run Sets whether the timer should start immediately.
   504     TimeReport(std::string title,std::ostream &os=std::cerr,bool run=true)
   505       : Timer(run), _title(title), _os(os){}
   506     ///Destructor that prints the ellapsed time
   507     ~TimeReport()
   508     {
   509       _os << _title << *this << std::endl;
   510     }
   511   };
   512 
   513   ///'Do nothing' version of TimeReport
   514 
   515   ///\sa TimeReport
   516   ///
   517   class NoTimeReport
   518   {
   519   public:
   520     ///\e
   521     NoTimeReport(std::string,std::ostream &,bool) {}
   522     ///\e
   523     NoTimeReport(std::string,std::ostream &) {}
   524     ///\e
   525     NoTimeReport(std::string) {}
   526     ///\e Do nothing.
   527     ~NoTimeReport() {}
   528 
   529     operator TimeStamp () const { return TimeStamp(); }
   530     void reset() {}
   531     void start() {}
   532     void stop() {}
   533     void halt() {}
   534     int running() { return 0; }
   535     void restart() {}
   536     double userTime() const { return 0; }
   537     double systemTime() const { return 0; }
   538     double cUserTime() const { return 0; }
   539     double cSystemTime() const { return 0; }
   540     double realTime() const { return 0; }
   541   };
   542 
   543   ///Tool to measure the running time more exactly.
   544 
   545   ///This function calls \c f several times and returns the average
   546   ///running time. The number of the executions will be choosen in such a way
   547   ///that the full real running time will be roughly between \c min_time
   548   ///and <tt>2*min_time</tt>.
   549   ///\param f the function object to be measured.
   550   ///\param min_time the minimum total running time.
   551   ///\retval num if it is not \c NULL, then the actual
   552   ///        number of execution of \c f will be written into <tt>*num</tt>.
   553   ///\retval full_time if it is not \c NULL, then the actual
   554   ///        total running time will be written into <tt>*full_time</tt>.
   555   ///\return The average running time of \c f.
   556 
   557   template<class F>
   558   TimeStamp runningTimeTest(F f,double min_time=10,unsigned int *num = NULL,
   559                             TimeStamp *full_time=NULL)
   560   {
   561     TimeStamp full;
   562     unsigned int total=0;
   563     Timer t;
   564     for(unsigned int tn=1;tn <= 1U<<31 && full.realTime()<=min_time; tn*=2) {
   565       for(;total<tn;total++) f();
   566       full=t;
   567     }
   568     if(num) *num=total;
   569     if(full_time) *full_time=full;
   570     return full/total;
   571   }
   572 
   573   /// @}
   574 
   575 
   576 } //namespace lemon
   577 
   578 #endif //LEMON_TIME_MEASURE_H