1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
19 #ifndef LEMON_TIME_MEASURE_H
20 #define LEMON_TIME_MEASURE_H
24 ///\brief Tools for measuring cpu usage
27 #include <lemon/bits/windows.h>
30 #include <sys/times.h>
37 #include <lemon/math.h>
41 /// \addtogroup timecount
44 /// A class to store (cpu)time instances.
46 /// This class stores five time values.
49 /// - a system cpu time
50 /// - a user cpu time of children
51 /// - a system cpu time of children
53 /// TimeStamp's can be added to or substracted from each other and
54 /// they can be pushed to a stream.
56 /// In most cases, perhaps the \ref Timer or the \ref TimeReport
57 /// class is what you want to use instead.
68 ///Display format specifier
73 /// Reports all measured values
75 /// Only real time and an error indicator is displayed
80 static Format _format;
83 utime = stime = cutime = cstime = rtime = 0;
92 ///The output format is global for all timestamp instances.
93 static void format(Format f) { _format = f; }
94 ///Retrieve the current output format
96 ///Retrieve the current output format
98 ///The output format is global for all timestamp instances.
99 static Format format() { return _format; }
102 ///Read the current time values of the process
107 gettimeofday(&tv, 0);
108 rtime=tv.tv_sec+double(tv.tv_usec)/1e6;
111 double tck=sysconf(_SC_CLK_TCK);
113 utime=ts.tms_utime/tck;
114 stime=ts.tms_stime/tck;
115 cutime=ts.tms_cutime/tck;
116 cstime=ts.tms_cstime/tck;
118 bits::getWinProcTimes(rtime, utime, stime, cutime, cstime);
122 /// Constructor initializing with zero
125 ///Constructor initializing with the current time values of the process
126 TimeStamp(void *) { stamp();}
128 ///Set every time value to zero
129 TimeStamp &reset() {_reset();return *this;}
132 TimeStamp &operator+=(const TimeStamp &b)
142 TimeStamp operator+(const TimeStamp &b) const
148 TimeStamp &operator-=(const TimeStamp &b)
158 TimeStamp operator-(const TimeStamp &b) const
164 TimeStamp &operator*=(double b)
174 TimeStamp operator*(double b) const
179 friend TimeStamp operator*(double b,const TimeStamp &t);
181 TimeStamp &operator/=(double b)
191 TimeStamp operator/(double b) const
196 ///The time ellapsed since the last call of stamp()
197 TimeStamp ellapsed() const
203 friend std::ostream& operator<<(std::ostream& os,const TimeStamp &t);
205 ///Gives back the user time of the process
206 double userTime() const
210 ///Gives back the system time of the process
211 double systemTime() const
215 ///Gives back the user time of the process' children
217 ///\note On <tt>WIN32</tt> platform this value is not calculated.
219 double cUserTime() const
223 ///Gives back the user time of the process' children
225 ///\note On <tt>WIN32</tt> platform this value is not calculated.
227 double cSystemTime() const
231 ///Gives back the real time
232 double realTime() const {return rtime;}
235 inline TimeStamp operator*(double b,const TimeStamp &t)
240 ///Prints the time counters
242 ///Prints the time counters in the following form:
244 /// <tt>u: XX.XXs s: XX.XXs cu: XX.XXs cs: XX.XXs real: XX.XXs</tt>
246 /// where the values are the
247 /// \li \c u: user cpu time,
248 /// \li \c s: system cpu time,
249 /// \li \c cu: user cpu time of children,
250 /// \li \c cs: system cpu time of children,
251 /// \li \c real: real time.
252 /// \relates TimeStamp
253 /// \note On <tt>WIN32</tt> platform the cummulative values are not
255 inline std::ostream& operator<<(std::ostream& os,const TimeStamp &t)
259 case TimeStamp::NORMAL:
260 os << "u: " << t.userTime() <<
261 "s, s: " << t.systemTime() <<
262 "s, cu: " << t.cUserTime() <<
263 "s, cs: " << t.cSystemTime() <<
264 "s, real: " << t.realTime() << "s";
266 case TimeStamp::SHORT:
267 double total = t.userTime()+t.systemTime()+
268 t.cUserTime()+t.cSystemTime();
270 << "s (err: " << round((t.realTime()-total)/
271 t.realTime()*10000)/100
278 ///Class for measuring the cpu time and real time usage of the process
280 ///Class for measuring the cpu time and real time usage of the process.
281 ///It is quite easy-to-use, here is a short example.
283 /// #include<lemon/time_measure.h>
284 /// #include<iostream>
293 /// std::cout << t << '\n';
295 /// doSomethingElse();
296 /// std::cout << t << '\n';
303 ///The \ref Timer can also be \ref stop() "stopped" and
304 ///\ref start() "started" again, so it is possible to compute collected
307 ///\warning Depending on the operation system and its actual configuration
308 ///the time counters have a certain (10ms on a typical Linux system)
310 ///Therefore this tool is not appropriate to measure very short times.
311 ///Also, if you start and stop the timer very frequently, it could lead to
312 ///distorted results.
314 ///\note If you want to measure the running time of the execution of a certain
315 ///function, consider the usage of \ref TimeReport instead.
320 int _running; //Timer is running iff _running>0; (_running>=0 always holds)
321 TimeStamp start_time; //This is the relativ start-time if the timer
322 //is _running, the collected _running time otherwise.
324 void _reset() {if(_running) start_time.stamp(); else start_time.reset();}
329 ///\param run indicates whether or not the timer starts immediately.
331 Timer(bool run=true) :_running(run) {_reset();}
333 ///\name Control the State of the Timer
334 ///Basically a Timer can be either running or stopped,
335 ///but it provides a bit finer control on the execution.
336 ///The \ref lemon::Timer "Timer" also counts the number of
337 ///\ref lemon::Timer::start() "start()" executions, and it stops
338 ///only after the same amount (or more) \ref lemon::Timer::stop()
339 ///"stop()"s. This can be useful e.g. to compute the running time
340 ///of recursive functions.
344 ///Reset and stop the time counters
346 ///This function resets and stops the time counters
354 ///Start the time counters
356 ///This function starts the time counters.
358 ///If the timer is started more than ones, it will remain running
359 ///until the same amount of \ref stop() is called.
363 if(_running) _running++;
368 start_time=t-start_time;
373 ///Stop the time counters
375 ///This function stops the time counters. If start() was executed more than
376 ///once, then the same number of stop() execution is necessary the really
386 if(_running && !--_running) {
389 start_time=t-start_time;
393 ///Halt (i.e stop immediately) the time counters
395 ///This function stops immediately the time counters, i.e. <tt>t.halt()</tt>
397 ///equivalent of the following.
399 /// while(t.running()) t.stop()
413 start_time=t-start_time;
417 ///Returns the running state of the timer
419 ///This function returns the number of stop() exections that is
420 ///necessary to really stop the timer.
421 ///For example, the timer
422 ///is running if and only if the return value is \c true
423 ///(i.e. greater than
425 int running() { return _running; }
428 ///Restart the time counters
430 ///This function is a shorthand for
431 ///a reset() and a start() calls.
441 ///\name Query Functions for the Ellapsed Time
445 ///Gives back the ellapsed user time of the process
446 double userTime() const
448 return operator TimeStamp().userTime();
450 ///Gives back the ellapsed system time of the process
451 double systemTime() const
453 return operator TimeStamp().systemTime();
455 ///Gives back the ellapsed user time of the process' children
457 ///\note On <tt>WIN32</tt> platform this value is not calculated.
459 double cUserTime() const
461 return operator TimeStamp().cUserTime();
463 ///Gives back the ellapsed user time of the process' children
465 ///\note On <tt>WIN32</tt> platform this value is not calculated.
467 double cSystemTime() const
469 return operator TimeStamp().cSystemTime();
471 ///Gives back the ellapsed real time
472 double realTime() const
474 return operator TimeStamp().realTime();
476 ///Computes the ellapsed time
478 ///This conversion computes the ellapsed time, therefore you can print
479 ///the ellapsed time like this.
483 /// std::cout << t << '\n';
485 operator TimeStamp () const
489 return _running?t-start_time:start_time;
496 ///Same as Timer but prints a report on destruction.
498 ///Same as \ref Timer but prints a report on destruction.
499 ///This example shows its usage.
501 /// void myAlg(ListGraph &g,int n)
503 /// TimeReport tr("Running time of myAlg: ");
504 /// ... //Here comes the algorithm
510 class TimeReport : public Timer
519 ///\param title This text will be printed before the ellapsed time.
520 ///\param os The stream to print the report to.
521 ///\param run Sets whether the timer should start immediately.
522 ///\param active Sets whether the report should actually be printed
524 TimeReport(std::string title,std::ostream &os=std::cerr,bool run=true,
526 : Timer(run), _title(title), _os(os), _active(active) {}
527 ///Destructor that prints the ellapsed time
530 if(_active) _os << _title << *this << std::endl;
533 ///Retrieve the activity status
537 bool active() const { return _active; }
538 ///Set the activity status
540 /// This function set whether the time report should actually be printed
542 void active(bool a) { _active=a; }
545 ///'Do nothing' version of TimeReport
553 NoTimeReport(std::string,std::ostream &,bool) {}
555 NoTimeReport(std::string,std::ostream &) {}
557 NoTimeReport(std::string) {}
561 operator TimeStamp () const { return TimeStamp(); }
566 int running() { return 0; }
568 double userTime() const { return 0; }
569 double systemTime() const { return 0; }
570 double cUserTime() const { return 0; }
571 double cSystemTime() const { return 0; }
572 double realTime() const { return 0; }
575 ///Tool to measure the running time more exactly.
577 ///This function calls \c f several times and returns the average
578 ///running time. The number of the executions will be choosen in such a way
579 ///that the full real running time will be roughly between \c min_time
580 ///and <tt>2*min_time</tt>.
581 ///\param f the function object to be measured.
582 ///\param min_time the minimum total running time.
583 ///\retval num if it is not \c NULL, then the actual
584 /// number of execution of \c f will be written into <tt>*num</tt>.
585 ///\retval full_time if it is not \c NULL, then the actual
586 /// total running time will be written into <tt>*full_time</tt>.
587 ///\return The average running time of \c f.
590 TimeStamp runningTimeTest(F f,double min_time=10,unsigned int *num = NULL,
591 TimeStamp *full_time=NULL)
594 unsigned int total=0;
596 for(unsigned int tn=1;tn <= 1U<<31 && full.realTime()<=min_time; tn*=2) {
597 for(;total<tn;total++) f();
601 if(full_time) *full_time=full;
610 #endif //LEMON_TIME_MEASURE_H