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