Teuchos Package Browser (Single Doxygen Collection)  Version of the Day
Teuchos_TimeMonitor.cpp
Go to the documentation of this file.
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Teuchos: Common Tools Package
5 // Copyright (2004) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ***********************************************************************
40 // @HEADER
41 
42 #include "Teuchos_TimeMonitor.hpp"
43 #include "Teuchos_CommHelpers.hpp"
44 #include "Teuchos_DefaultComm.hpp"
45 #include "Teuchos_TableColumn.hpp"
46 #include "Teuchos_TableFormat.hpp"
48 #include "Teuchos_ScalarTraits.hpp"
49 #include <functional>
50 
51 
52 namespace Teuchos {
105  template<class Ordinal, class ScalarType, class IndexType>
106  class MaxLoc :
107  public ValueTypeReductionOp<Ordinal, std::pair<ScalarType, IndexType> > {
108  public:
109  void
110  reduce (const Ordinal count,
111  const std::pair<ScalarType, IndexType> inBuffer[],
112  std::pair<ScalarType, IndexType> inoutBuffer[]) const;
113  };
114 
115  template<class Ordinal>
116  class MaxLoc<Ordinal, double, int> :
117  public ValueTypeReductionOp<Ordinal, std::pair<double, int> > {
118  public:
119  void
120  reduce (const Ordinal count,
121  const std::pair<double, int> inBuffer[],
122  std::pair<double, int> inoutBuffer[]) const
123  {
124  for (Ordinal ind = 0; ind < count; ++ind) {
125  const std::pair<double, int>& in = inBuffer[ind];
126  std::pair<double, int>& inout = inoutBuffer[ind];
127 
128  if (in.first > inout.first) {
129  inout.first = in.first;
130  inout.second = in.second;
131  } else if (in.first < inout.first) {
132  // Don't need to do anything; inout has the values.
133  } else { // equal, or at least one is NaN.
134  inout.first = in.first;
135  inout.second = std::min (in.second, inout.second);
136  }
137  }
138  }
139  };
140 
167  template<class Ordinal, class ScalarType, class IndexType>
168  class MinLoc :
169  public ValueTypeReductionOp<Ordinal, std::pair<ScalarType, IndexType> > {
170  public:
171  void
172  reduce (const Ordinal count,
173  const std::pair<ScalarType, IndexType> inBuffer[],
174  std::pair<ScalarType, IndexType> inoutBuffer[]) const;
175  };
176 
177  template<class Ordinal>
178  class MinLoc<Ordinal, double, int> :
179  public ValueTypeReductionOp<Ordinal, std::pair<double, int> > {
180  public:
181  void
182  reduce (const Ordinal count,
183  const std::pair<double, int> inBuffer[],
184  std::pair<double, int> inoutBuffer[]) const
185  {
186  for (Ordinal ind = 0; ind < count; ++ind) {
187  const std::pair<double, int>& in = inBuffer[ind];
188  std::pair<double, int>& inout = inoutBuffer[ind];
189 
190  if (in.first < inout.first) {
191  inout.first = in.first;
192  inout.second = in.second;
193  } else if (in.first > inout.first) {
194  // Don't need to do anything; inout has the values.
195  } else { // equal, or at least one is NaN.
196  inout.first = in.first;
197  inout.second = std::min (in.second, inout.second);
198  }
199  }
200  }
201  };
202 
203  // Typedef used internally by TimeMonitor::summarize() and its
204  // helper functions. The map is keyed on timer label (a string).
205  // Each value is a pair: (total number of seconds over all calls to
206  // that timer, total number of calls to that timer).
207  typedef std::map<std::string, std::pair<double, int> > timer_map_t;
208 
209  TimeMonitor::TimeMonitor (Time& timer, bool reset)
210  : PerformanceMonitorBase<Time>(timer, reset)
211  {
212  if (!isRecursiveCall()) counter().start(reset);
213  }
214 
216  if (!isRecursiveCall()) counter().stop();
217  }
218 
219  void
220  TimeMonitor::disableTimer (const std::string& name)
221  {
222  RCP<Time> timer = lookupCounter (name);
224  timer == null, std::invalid_argument,
225  "TimeMonitor::disableTimer: Invalid timer \"" << name << "\"");
226  timer->disable ();
227  }
228 
229  void
230  TimeMonitor::enableTimer (const std::string& name)
231  {
232  RCP<Time> timer = lookupCounter (name);
234  timer == null, std::invalid_argument,
235  "TimeMonitor::enableTimer: Invalid timer \"" << name << "\"");
236  timer->enable ();
237  }
238 
239  void
241  {
242  typedef std::map<std::string, RCP<Time> > map_type;
243  typedef map_type::iterator iter_type;
244  map_type& ctrs = counters ();
245 
246  // In debug mode, loop first to check whether any of the timers
247  // are running, before resetting them. This ensures that this
248  // method satisfies the strong exception guarantee (either it
249  // completes normally, or there are no side effects).
250 #ifdef TEUCHOS_DEBUG
251  for (iter_type it = ctrs.begin(); it != ctrs.end(); ++it) {
252  // We throw a runtime_error rather than a logic_error, because
253  // logic_error suggests a bug in the implementation of
254  // TimeMonitor. Calling zeroOutTimers() when a timer is running
255  // is not TimeMonitor's fault.
257  it->second->isRunning (), std::runtime_error,
258  "Timer \"" << it->second->name () << "\" is currently running. "
259  "You are not allowed to reset running timers.");
260  }
261 #endif // TEUCHOS_DEBUG
262 
263  for (iter_type it = ctrs.begin(); it != ctrs.end(); ++it) {
264  it->second->reset ();
265  }
266  }
267 
268  // An anonymous namespace is the standard way of limiting linkage of
269  // its contained routines to file scope.
270  namespace {
271  // \brief Return an "empty" local timer datum.
272  //
273  // "Empty" means the datum has zero elapsed time and zero call
274  // count. This function does not actually create a timer.
275  //
276  // \param name The timer's name.
277  std::pair<std::string, std::pair<double, int> >
278  makeEmptyTimerDatum (const std::string& name)
279  {
280  return std::make_pair (name, std::make_pair (double(0), int(0)));
281  }
282 
283  // \fn collectLocalTimerData
284  // \brief Collect and sort local timer data by timer names.
285  //
286  // \param localData [out] Map whose keys are the timer names, and
287  // whose value for each key is the total elapsed time (in
288  // seconds) and the call count for the timer with that name.
289  //
290  // \param localCounters [in] Timers from which to extract data.
291  //
292  // \param filter [in] Filter for timer labels. If filter is not
293  // empty, this method will only collect data for local timers
294  // whose labels begin with this string.
295  //
296  // Extract the total elapsed time and call count from each timer
297  // in the given array. Merge results for timers with duplicate
298  // labels, by summing their total elapsed times and call counts
299  // pairwise.
300  void
301  collectLocalTimerData (timer_map_t& localData,
302  const std::map<std::string, RCP<Time> >& localCounters,
303  const std::string& filter="")
304  {
305  using std::make_pair;
306  typedef timer_map_t::iterator iter_t;
307 
308  timer_map_t theLocalData;
309  for (std::map<std::string, RCP<Time> >::const_iterator it = localCounters.begin();
310  it != localCounters.end(); ++it) {
311  const std::string& name = it->second->name ();
312 
313  // Filter current timer name, if provided filter is nonempty.
314  // Filter string must _start_ the timer label, not just be in it.
315  const bool skipThisOne = (filter != "" && name.find (filter) != 0);
316  if (! skipThisOne) {
317  const double timing = it->second->totalElapsedTime ();
318  const int numCalls = it->second->numCalls ();
319 
320  // Merge timers with duplicate labels, by summing their
321  // total elapsed times and call counts.
322  iter_t loc = theLocalData.find (name);
323  if (loc == theLocalData.end()) {
324  // Use loc as an insertion location hint.
325  theLocalData.insert (loc, make_pair (name, make_pair (timing, numCalls)));
326  }
327  else {
328  loc->second.first += timing;
329  loc->second.second += numCalls;
330  }
331  }
332  }
333  // This avoids copying the map, and also makes this method
334  // satisfy the strong exception guarantee.
335  localData.swap (theLocalData);
336  }
337 
338  // \brief Locally filter out timer data with zero call counts.
339  //
340  // \param timerData [in/out]
341  void
342  filterZeroData (timer_map_t& timerData)
343  {
344  // FIXME (mfh 15 Mar 2013) Should use std::map::erase with
345  // iterator hint, instead of rebuilding the map completely.
346  timer_map_t newTimerData;
347  for (timer_map_t::const_iterator it = timerData.begin();
348  it != timerData.end(); ++it) {
349  if (it->second.second > 0) {
350  newTimerData[it->first] = it->second;
351  }
352  }
353  timerData.swap (newTimerData);
354  }
355 
377  void
378  collectLocalTimerDataAndNames (timer_map_t& localTimerData,
379  Array<std::string>& localTimerNames,
380  const std::map<std::string, RCP<Time> >& localTimers,
381  const bool writeZeroTimers,
382  const std::string& filter="")
383  {
384  // Collect and sort local timer data by timer names.
385  collectLocalTimerData (localTimerData, localTimers, filter);
386 
387  // Filter out zero data locally first. This ensures that if we
388  // are writing global stats, and if a timer name exists in the
389  // set of global names, then that timer has a nonzero call count
390  // on at least one MPI process.
391  if (! writeZeroTimers) {
392  filterZeroData (localTimerData);
393  }
394 
395  // Extract the set of local timer names. The std::map keeps
396  // them sorted alphabetically.
397  localTimerNames.reserve (localTimerData.size());
398  for (timer_map_t::const_iterator it = localTimerData.begin();
399  it != localTimerData.end(); ++it) {
400  localTimerNames.push_back (it->first);
401  }
402  }
403 
438  void
439  collectGlobalTimerData (timer_map_t& globalTimerData,
440  Array<std::string>& globalTimerNames,
441  timer_map_t& localTimerData,
442  Array<std::string>& localTimerNames,
443  Ptr<const Comm<int> > comm,
444  const bool alwaysWriteLocal,
445  const ECounterSetOp setOp)
446  {
447  // There may be some global timers that are not local timers on
448  // the calling MPI process(es). In that case, if
449  // alwaysWriteLocal is true, then we need to fill in the
450  // "missing" local timers. That will ensure that both global
451  // and local timer columns in the output table have the same
452  // number of rows. The collectLocalTimerDataAndNames() method
453  // may have already filtered out local timers with zero call
454  // counts (if its writeZeroTimers argument was false), but we
455  // won't be filtering again. Thus, any local timer data we
456  // insert here won't get filtered out.
457  //
458  // Note that calling summarize() with writeZeroTimers == false
459  // will still do what it says, even if we insert local timers
460  // with zero call counts here.
461 
462  // This does the correct and inexpensive thing (just copies the
463  // timer data) if numProcs == 1. Otherwise, it initiates a
464  // communication with \f$O(\log P)\f$ messages along the
465  // critical path, where \f$P\f$ is the number of participating
466  // processes.
467  mergeCounterNames (*comm, localTimerNames, globalTimerNames, setOp);
468 
469 #ifdef TEUCHOS_DEBUG
470  {
471  // Sanity check that all processes have the name number of
472  // global timer names.
473  const timer_map_t::size_type myNumGlobalNames = globalTimerNames.size();
474  timer_map_t::size_type minNumGlobalNames = 0;
475  timer_map_t::size_type maxNumGlobalNames = 0;
476  reduceAll (*comm, REDUCE_MIN, myNumGlobalNames,
477  outArg (minNumGlobalNames));
478  reduceAll (*comm, REDUCE_MAX, myNumGlobalNames,
479  outArg (maxNumGlobalNames));
480  TEUCHOS_TEST_FOR_EXCEPTION(minNumGlobalNames != maxNumGlobalNames,
481  std::logic_error, "Min # global timer names = " << minNumGlobalNames
482  << " != max # global timer names = " << maxNumGlobalNames
483  << ". Please report this bug to the Teuchos developers.");
484  TEUCHOS_TEST_FOR_EXCEPTION(myNumGlobalNames != minNumGlobalNames,
485  std::logic_error, "My # global timer names = " << myNumGlobalNames
486  << " != min # global timer names = " << minNumGlobalNames
487  << ". Please report this bug to the Teuchos developers.");
488  }
489 #endif // TEUCHOS_DEBUG
490 
491  // mergeCounterNames() just merges the counters' names, not
492  // their actual data. Now we need to fill globalTimerData with
493  // this process' timer data for the timers in globalTimerNames.
494  //
495  // All processes need the full list of global timers, since
496  // there may be some global timers that are not local timers.
497  // That's why mergeCounterNames() has to be an all-reduce, not
498  // just a reduction to Proc 0.
499  //
500  // Insertion optimization: if the iterator given to map::insert
501  // points right before where we want to insert, insertion is
502  // O(1). globalTimerNames is sorted, so feeding the iterator
503  // output of map::insert into the next invocation's input should
504  // make the whole insertion O(N) where N is the number of
505  // entries in globalTimerNames.
506  timer_map_t::iterator globalMapIter = globalTimerData.begin();
507  timer_map_t::iterator localMapIter;
508  for (Array<string>::const_iterator it = globalTimerNames.begin();
509  it != globalTimerNames.end(); ++it) {
510  const std::string& globalName = *it;
511  localMapIter = localTimerData.find (globalName);
512 
513  if (localMapIter == localTimerData.end()) {
514  if (alwaysWriteLocal) {
515  // If there are some global timers that are not local
516  // timers, and if we want to print local timers, we insert
517  // a local timer datum with zero elapsed time and zero
518  // call count into localTimerData as well. This will
519  // ensure that both global and local timer columns in the
520  // output table have the same number of rows.
521  //
522  // We really only need to do this on Proc 0, which is the
523  // only process that currently may print local timers.
524  // However, we do it on all processes, just in case
525  // someone later wants to modify this function to print
526  // out local timer data for some process other than Proc
527  // 0. This extra computation won't affect the cost along
528  // the critical path, for future computations in which
529  // Proc 0 participates.
530  localMapIter = localTimerData.insert (localMapIter, makeEmptyTimerDatum (globalName));
531 
532  // Make sure the missing global name gets added to the
533  // list of local names. We'll re-sort the list of local
534  // names below.
535  localTimerNames.push_back (globalName);
536  }
537  // There's a global timer that's not a local timer. Add it
538  // to our pre-merge version of the global timer data so that
539  // we can safely merge the global timer data later.
540  globalMapIter = globalTimerData.insert (globalMapIter, makeEmptyTimerDatum (globalName));
541  }
542  else {
543  // We have this global timer name in our local timer list.
544  // Fill in our pre-merge version of the global timer data
545  // with our local data.
546  globalMapIter = globalTimerData.insert (globalMapIter, std::make_pair (globalName, localMapIter->second));
547  }
548  }
549 
550  if (alwaysWriteLocal) {
551  // Re-sort the list of local timer names, since we may have
552  // inserted "missing" names above.
553  std::sort (localTimerNames.begin(), localTimerNames.end());
554  }
555 
556 #ifdef TEUCHOS_DEBUG
557  {
558  // Sanity check that all processes have the name number of
559  // global timers.
560  const timer_map_t::size_type myNumGlobalTimers = globalTimerData.size();
561  timer_map_t::size_type minNumGlobalTimers = 0;
562  timer_map_t::size_type maxNumGlobalTimers = 0;
563  reduceAll (*comm, REDUCE_MIN, myNumGlobalTimers,
564  outArg (minNumGlobalTimers));
565  reduceAll (*comm, REDUCE_MAX, myNumGlobalTimers,
566  outArg (maxNumGlobalTimers));
567  TEUCHOS_TEST_FOR_EXCEPTION(minNumGlobalTimers != maxNumGlobalTimers,
568  std::logic_error, "Min # global timers = " << minNumGlobalTimers
569  << " != max # global timers = " << maxNumGlobalTimers
570  << ". Please report this bug to the Teuchos developers.");
571  TEUCHOS_TEST_FOR_EXCEPTION(myNumGlobalTimers != minNumGlobalTimers,
572  std::logic_error, "My # global timers = " << myNumGlobalTimers
573  << " != min # global timers = " << minNumGlobalTimers
574  << ". Please report this bug to the Teuchos developers.");
575  }
576 #endif // TEUCHOS_DEBUG
577  }
578 
616  void
617  computeGlobalTimerStats (stat_map_type& statData,
618  std::vector<std::string>& statNames,
619  Ptr<const Comm<int> > comm,
620  const timer_map_t& globalTimerData)
621  {
622  using Teuchos::ScalarTraits;
623 
624  const int numTimers = static_cast<int> (globalTimerData.size());
625  const int numProcs = comm->getSize();
626 
627  // Extract pre-reduction timings and call counts into a
628  // sequential array. This array will be in the same order as
629  // the global timer names are in the map.
630  Array<std::pair<double, int> > timingsAndCallCounts;
631  timingsAndCallCounts.reserve (numTimers);
632  for (timer_map_t::const_iterator it = globalTimerData.begin();
633  it != globalTimerData.end(); ++it) {
634  timingsAndCallCounts.push_back (it->second);
635  }
636 
637  // For each timer name, compute the min timing and its
638  // corresponding call count. If two processes have the same
639  // timing but different call counts, the minimum call count will
640  // be used.
641  Array<std::pair<double, int> > minTimingsAndCallCounts (numTimers);
642  if (numTimers > 0) {
643  reduceAll (*comm, MinLoc<int, double, int>(), numTimers,
644  &timingsAndCallCounts[0], &minTimingsAndCallCounts[0]);
645  }
646 
647  // For each timer name, compute the max timing and its
648  // corresponding call count. If two processes have the same
649  // timing but different call counts, the minimum call count will
650  // be used.
651  Array<std::pair<double, int> > maxTimingsAndCallCounts (numTimers);
652  if (numTimers > 0) {
653  reduceAll (*comm, MaxLoc<int, double, int>(), numTimers,
654  &timingsAndCallCounts[0], &maxTimingsAndCallCounts[0]);
655  }
656 
657  // For each timer name, compute the mean-over-processes timing,
658  // the mean call count, and the mean-over-call-counts timing.
659  // The mean call count is reported as a double to allow a
660  // fractional value.
661  //
662  // Each local timing is really the total timing over all local
663  // invocations. The number of local invocations is the call
664  // count. Thus, the mean-over-call-counts timing is the sum of
665  // all the timings (over all processes), divided by the sum of
666  // all the call counts (over all processes). We compute it in a
667  // different way to over unnecessary overflow.
668  Array<double> meanOverCallCountsTimings (numTimers);
669  Array<double> meanOverProcsTimings (numTimers);
670  Array<double> meanCallCounts (numTimers);
671  {
672  // When summing, first scale by the number of processes. This
673  // avoids unnecessary overflow, and also gives us the mean
674  // call count automatically.
675  Array<double> scaledTimings (numTimers);
676  Array<double> scaledCallCounts (numTimers);
677  const double P = static_cast<double> (numProcs);
678  for (int k = 0; k < numTimers; ++k) {
679  const double timing = timingsAndCallCounts[k].first;
680  const double callCount = static_cast<double> (timingsAndCallCounts[k].second);
681 
682  scaledTimings[k] = timing / P;
683  scaledCallCounts[k] = callCount / P;
684  }
685  if (numTimers > 0) {
686  reduceAll (*comm, REDUCE_SUM, numTimers, &scaledTimings[0],
687  &meanOverProcsTimings[0]);
688  reduceAll (*comm, REDUCE_SUM, numTimers, &scaledCallCounts[0],
689  &meanCallCounts[0]);
690  }
691  // We don't have to undo the scaling for the mean timings;
692  // just divide by the scaled call count.
693  for (int k = 0; k < numTimers; ++k) {
694  if (meanCallCounts[k] > ScalarTraits<double>::zero ()) {
695  meanOverCallCountsTimings[k] = meanOverProcsTimings[k] / meanCallCounts[k];
696  }
697  else {
698  meanOverCallCountsTimings[k] = ScalarTraits<double>::zero ();
699  }
700  }
701  }
702 
703  // Reformat the data into the map of statistics. Be sure that
704  // each value (the std::vector of (timing, call count) pairs,
705  // each entry of which is a different statistic) preserves the
706  // order of statNames.
707  statNames.resize (4);
708  statNames[0] = "MinOverProcs";
709  statNames[1] = "MeanOverProcs";
710  statNames[2] = "MaxOverProcs";
711  statNames[3] = "MeanOverCallCounts";
712 
713  stat_map_type::iterator statIter = statData.end();
714  timer_map_t::const_iterator it = globalTimerData.begin();
715  for (int k = 0; it != globalTimerData.end(); ++k, ++it) {
716  std::vector<std::pair<double, double> > curData (4);
717  curData[0] = minTimingsAndCallCounts[k];
718  curData[1] = std::make_pair (meanOverProcsTimings[k], meanCallCounts[k]);
719  curData[2] = maxTimingsAndCallCounts[k];
720  curData[3] = std::make_pair (meanOverCallCountsTimings[k], meanCallCounts[k]);
721 
722  // statIter gives an insertion location hint that makes each
723  // insertion O(1), since we remember the location of the last
724  // insertion.
725  statIter = statData.insert (statIter, std::make_pair (it->first, curData));
726  }
727  }
728 
729 
747  getDefaultComm ()
748  {
749  // The default communicator. If Trilinos was built with MPI
750  // enabled, this should be MPI_COMM_WORLD. (If MPI has not yet
751  // been initialized, it's not valid to use the communicator!)
752  // Otherwise, this should be a "serial" (no MPI, one "process")
753  // communicator.
755 
756 #ifdef HAVE_MPI
757  {
758  int mpiHasBeenStarted = 0;
759  MPI_Initialized (&mpiHasBeenStarted);
760  if (! mpiHasBeenStarted) {
761  // Make pComm a new "serial communicator."
762  comm = rcp_implicit_cast<const Comm<int> > (rcp (new SerialComm<int> ()));
763  }
764  }
765 #endif // HAVE_MPI
766  return comm;
767  }
768 
769  } // namespace (anonymous)
770 
771 
772  void
774  std::vector<std::string>& statNames,
775  Ptr<const Comm<int> > comm,
776  const ECounterSetOp setOp,
777  const std::string& filter)
778  {
779  // Collect local timer data and names. Filter out timers with
780  // zero call counts if writeZeroTimers is false. Also, apply the
781  // timer label filter at this point, so we don't have to compute
782  // statistics on timers we don't want to display anyway.
783  timer_map_t localTimerData;
784  Array<std::string> localTimerNames;
785  const bool writeZeroTimers = false;
786  collectLocalTimerDataAndNames (localTimerData, localTimerNames,
787  counters(), writeZeroTimers, filter);
788  // Merge the local timer data and names into global timer data and
789  // names.
790  timer_map_t globalTimerData;
791  Array<std::string> globalTimerNames;
792  const bool alwaysWriteLocal = false;
793  collectGlobalTimerData (globalTimerData, globalTimerNames,
794  localTimerData, localTimerNames,
795  comm, alwaysWriteLocal, setOp);
796  // Compute statistics on the data.
797  computeGlobalTimerStats (statData, statNames, comm, globalTimerData);
798  }
799 
800 
801  void
803  std::ostream& out,
804  const bool alwaysWriteLocal,
805  const bool writeGlobalStats,
806  const bool writeZeroTimers,
807  const ECounterSetOp setOp,
808  const std::string& filter)
809  {
810  //
811  // We can't just call computeGlobalTimerStatistics(), since
812  // summarize() has different options that affect whether global
813  // statistics are computed and printed.
814  //
815  const int numProcs = comm->getSize();
816  const int myRank = comm->getRank();
817 
818  // Collect local timer data and names. Filter out timers with
819  // zero call counts if writeZeroTimers is false. Also, apply the
820  // timer label filter at this point, so we don't have to compute
821  // statistics on timers we don't want to display anyway.
822  timer_map_t localTimerData;
823  Array<std::string> localTimerNames;
824  collectLocalTimerDataAndNames (localTimerData, localTimerNames,
825  counters(), writeZeroTimers, filter);
826 
827  // If we're computing global statistics, merge the local timer
828  // data and names into global timer data and names, and compute
829  // global timer statistics. Otherwise, leave the global data
830  // empty.
831  timer_map_t globalTimerData;
832  Array<std::string> globalTimerNames;
833  stat_map_type statData;
834  std::vector<std::string> statNames;
835  if (writeGlobalStats) {
836  collectGlobalTimerData (globalTimerData, globalTimerNames,
837  localTimerData, localTimerNames,
838  comm, alwaysWriteLocal, setOp);
839  // Compute statistics on the data, but only if the communicator
840  // contains more than one process. Otherwise, statistics don't
841  // make sense and we don't print them (see below).
842  if (numProcs > 1) {
843  computeGlobalTimerStats (statData, statNames, comm, globalTimerData);
844  }
845  }
846 
847  // Precision of floating-point numbers in the table.
848  const int precision = format().precision();
849 
850  // All columns of the table, in order.
851  Array<TableColumn> tableColumns;
852 
853  // Labels of all the columns of the table.
854  // We will append to this when we add each column.
855  Array<std::string> titles;
856 
857  // Widths (in number of characters) of each column.
858  // We will append to this when we add each column.
859  Array<int> columnWidths;
860 
861  // Table column containing all timer names. If writeGlobalStats
862  // is true, we use the global timer names, otherwise we use the
863  // local timer names. We build the table on all processes
864  // redundantly, but only print on Rank 0.
865  {
866  titles.append ("Timer Name");
867 
868  // The column labels depend on whether we are computing global statistics.
869  TableColumn nameCol (writeGlobalStats ? globalTimerNames : localTimerNames);
870  tableColumns.append (nameCol);
871 
872  // Each column is as wide as it needs to be to hold both its
873  // title and all of the column data. This column's title is the
874  // current last entry of the titles array.
875  columnWidths.append (format().computeRequiredColumnWidth (titles.back(), nameCol));
876  }
877 
878  // Table column containing local timer stats, if applicable. We
879  // only write local stats if asked, only on MPI Proc 0, and only
880  // if there is more than one MPI process in the communicator
881  // (otherwise local stats == global stats, so we just print the
882  // global stats). In this case, we've padded the local data on
883  // Proc 0 if necessary to match the global timer list, so that the
884  // columns have the same number of rows.
885  if (alwaysWriteLocal && numProcs > 1 && myRank == 0) {
886  titles.append ("Local time (num calls)");
887 
888  // Copy local timer data out of the array-of-structs into
889  // separate arrays, for display in the table.
890  Array<double> localTimings;
891  Array<double> localNumCalls;
892  for (timer_map_t::const_iterator it = localTimerData.begin();
893  it != localTimerData.end(); ++it) {
894  localTimings.push_back (it->second.first);
895  localNumCalls.push_back (static_cast<double> (it->second.second));
896  }
897  TableColumn timeAndCalls (localTimings, localNumCalls, precision, true);
898  tableColumns.append (timeAndCalls);
899  columnWidths.append (format().computeRequiredColumnWidth (titles.back(), timeAndCalls));
900  }
901 
902  if (writeGlobalStats) {
903  // If there's only 1 process in the communicator, don't display
904  // statistics; statistics don't make sense in that case. Just
905  // display the timings and call counts. If there's more than 1
906  // process, do display statistics.
907  if (numProcs == 1) {
908  // Extract timings and the call counts from globalTimerData.
909  Array<double> globalTimings;
910  Array<double> globalNumCalls;
911  for (timer_map_t::const_iterator it = globalTimerData.begin();
912  it != globalTimerData.end(); ++it) {
913  globalTimings.push_back (it->second.first);
914  globalNumCalls.push_back (static_cast<double> (it->second.second));
915  }
916  // Print the table column.
917  titles.append ("Global time (num calls)");
918  TableColumn timeAndCalls (globalTimings, globalNumCalls, precision, true);
919  tableColumns.append (timeAndCalls);
920  columnWidths.append (format().computeRequiredColumnWidth (titles.back(), timeAndCalls));
921  }
922  else { // numProcs > 1
923  // Print a table column for each statistic. statNames and
924  // each value in statData use the same ordering, so we can
925  // iterate over valid indices of statNames to display the
926  // statistics in the right order.
927  const timer_map_t::size_type numGlobalTimers = globalTimerData.size();
928  for (std::vector<std::string>::size_type statInd = 0; statInd < statNames.size(); ++statInd) {
929  // Extract lists of timings and their call counts for the
930  // current statistic.
931  Array<double> statTimings (numGlobalTimers);
932  Array<double> statCallCounts (numGlobalTimers);
933  stat_map_type::const_iterator it = statData.begin();
934  for (int k = 0; it != statData.end(); ++it, ++k) {
935  statTimings[k] = (it->second[statInd]).first;
936  statCallCounts[k] = (it->second[statInd]).second;
937  }
938  // Print the table column.
939  const std::string& statisticName = statNames[statInd];
940  const std::string titleString = statisticName;
941  titles.append (titleString);
942  TableColumn timeAndCalls (statTimings, statCallCounts, precision, true);
943  tableColumns.append (timeAndCalls);
944  columnWidths.append (format().computeRequiredColumnWidth (titles.back(), timeAndCalls));
945  }
946  }
947  }
948 
949  // Print the whole table to the given output stream on MPI Rank 0.
950  format().setColumnWidths (columnWidths);
951  if (myRank == 0) {
952  std::ostringstream theTitle;
953  theTitle << "TimeMonitor results over " << numProcs << " processor"
954  << (numProcs > 1 ? "s" : "");
955  format().writeWholeTable (out, theTitle.str(), titles, tableColumns);
956  }
957  }
958 
959  void
960  TimeMonitor::summarize (std::ostream &out,
961  const bool alwaysWriteLocal,
962  const bool writeGlobalStats,
963  const bool writeZeroTimers,
964  const ECounterSetOp setOp,
965  const std::string& filter)
966  {
967  // The default communicator. If Trilinos was built with MPI
968  // enabled, this should be MPI_COMM_WORLD. Otherwise, this should
969  // be a "serial" (no MPI, one "process") communicator.
970  RCP<const Comm<int> > comm = getDefaultComm();
971 
972  summarize (comm.ptr(), out, alwaysWriteLocal,
973  writeGlobalStats, writeZeroTimers, setOp, filter);
974  }
975 
976  void
978  std::vector<std::string>& statNames,
979  const ECounterSetOp setOp,
980  const std::string& filter)
981  {
982  // The default communicator. If Trilinos was built with MPI
983  // enabled, this should be MPI_COMM_WORLD. Otherwise, this should
984  // be a "serial" (no MPI, one "process") communicator.
985  RCP<const Comm<int> > comm = getDefaultComm();
986 
987  computeGlobalTimerStatistics (statData, statNames, comm.ptr(), setOp, filter);
988  }
989 
990 
991  namespace {
1015  std::string
1016  quoteLabelForYaml (const std::string& label)
1017  {
1018  // YAML allows empty keys in key: value pairs. See Section 7.2
1019  // of the YAML 1.2 spec. We thus let an empty label pass
1020  // through without quoting or other special treatment.
1021  if (label.empty ()) {
1022  return label;
1023  }
1024 
1025  // Check whether the label is already quoted. If so, we don't
1026  // need to quote it again. However, we do need to quote any
1027  // quote symbols in the string inside the outer quotes.
1028  const bool alreadyQuoted = label.size () >= 2 &&
1029  label[0] == '"' && label[label.size() - 1] == '"';
1030 
1031  // We need to quote if there are any colons or (inner) quotes in
1032  // the string. We'll determine this as we read through the
1033  // string and escape any characters that need escaping.
1034  bool needToQuote = false;
1035 
1036  std::string out; // To fill with the return value
1037  out.reserve (label.size ());
1038 
1039  const size_t startPos = alreadyQuoted ? 1 : 0;
1040  const size_t endPos = alreadyQuoted ? label.size () - 1 : label.size ();
1041  for (size_t i = startPos; i < endPos; ++i) {
1042  const char c = label[i];
1043  if (c == '"' || c == '\\') {
1044  out.push_back ('\\'); // Escape the quote or backslash.
1045  needToQuote = true;
1046  }
1047  else if (c == ':') {
1048  needToQuote = true;
1049  }
1050  out.push_back (c);
1051  }
1052 
1053  if (needToQuote || alreadyQuoted) {
1054  // If the input string was already quoted, then out doesn't
1055  // include its quotes, so we have to add them back in.
1056  return "\"" + out + "\"";
1057  }
1058  else {
1059  return out;
1060  }
1061  }
1062 
1063  } // namespace (anonymous)
1064 
1065 
1066  void TimeMonitor::
1068  std::ostream &out,
1069  const ETimeMonitorYamlFormat yamlStyle,
1070  const std::string& filter)
1071  {
1072  using Teuchos::FancyOStream;
1073  using Teuchos::fancyOStream;
1074  using Teuchos::getFancyOStream;
1075  using Teuchos::OSTab;
1076  using Teuchos::RCP;
1077  using Teuchos::rcpFromRef;
1078  using std::endl;
1079  typedef std::vector<std::string>::size_type size_type;
1080 
1081  const bool compact = (yamlStyle == YAML_FORMAT_COMPACT);
1082 
1083  // const bool writeGlobalStats = true;
1084  // const bool writeZeroTimers = true;
1085  // const bool alwaysWriteLocal = false;
1086  const ECounterSetOp setOp = Intersection;
1087 
1088  stat_map_type statData;
1089  std::vector<std::string> statNames;
1090  computeGlobalTimerStatistics (statData, statNames, comm, setOp, filter);
1091 
1092  const int numProcs = comm->getSize();
1093 
1094  // HACK (mfh 20 Aug 2012) For some reason, creating OSTab with "-
1095  // " as the line prefix does not work, else I would prefer that
1096  // method for printing each line of a YAML block sequence (see
1097  // Section 8.2.1 of the YAML 1.2 spec).
1098  //
1099  // Also, I have to set the tab indent string here, rather than in
1100  // OSTab's constructor. This is because line prefix (which for
1101  // some reason is what OSTab's constructor takes, rather than tab
1102  // indent string) means something different from tab indent
1103  // string, and turning on the line prefix prints all sorts of
1104  // things including "|" for some reason.
1105  RCP<FancyOStream> pfout = getFancyOStream (rcpFromRef (out));
1106  pfout->setTabIndentStr (" ");
1107  FancyOStream& fout = *pfout;
1108 
1109  fout << "# Teuchos::TimeMonitor report" << endl
1110  << "---" << endl;
1111 
1112  // mfh 19 Aug 2012: An important goal of our chosen output format
1113  // was to minimize the nesting depth. We have managed to keep the
1114  // nesting depth to 3, which is the limit that the current version
1115  // of PylotDB imposes for its YAML input.
1116 
1117  // Outermost level is a dictionary. (Individual entries of a
1118  // dictionary do _not_ begin with "- ".) We always print the
1119  // outermost level in standard style, not flow style, for better
1120  // readability. We begin the outermost level with metadata.
1121  fout << "Output mode: " << (compact ? "compact" : "spacious") << endl
1122  << "Number of processes: " << numProcs << endl
1123  << "Time unit: s" << endl;
1124  // For a key: value pair where the value is a sequence or
1125  // dictionary on the following line, YAML requires a space after
1126  // the colon.
1127  fout << "Statistics collected: ";
1128  // Print list of the names of all the statistics we collected.
1129  if (compact) {
1130  fout << " [";
1131  for (size_type i = 0; i < statNames.size (); ++i) {
1132  fout << quoteLabelForYaml (statNames[i]);
1133  if (i + 1 < statNames.size ()) {
1134  fout << ", ";
1135  }
1136  }
1137  fout << "]" << endl;
1138  }
1139  else {
1140  fout << endl;
1141  OSTab tab1 (pfout);
1142  for (size_type i = 0; i < statNames.size (); ++i) {
1143  fout << "- " << quoteLabelForYaml (statNames[i]) << endl;
1144  }
1145  }
1146 
1147  // Print the list of timer names.
1148  //
1149  // It might be nicer instead to print a map from timer name to all
1150  // of its data, but keeping the maximum nesting depth small
1151  // ensures better compatibility with different parsing tools.
1152  fout << "Timer names: ";
1153  if (compact) {
1154  fout << " [";
1155  size_type ind = 0;
1156  for (stat_map_type::const_iterator it = statData.begin();
1157  it != statData.end(); ++it, ++ind) {
1158  fout << quoteLabelForYaml (it->first);
1159  if (ind + 1 < statData.size ()) {
1160  fout << ", ";
1161  }
1162  }
1163  fout << "]" << endl;
1164  }
1165  else {
1166  fout << endl;
1167  OSTab tab1 (pfout);
1168  for (stat_map_type::const_iterator it = statData.begin();
1169  it != statData.end(); ++it) {
1170  fout << "- " << quoteLabelForYaml (it->first) << endl;
1171  }
1172  }
1173 
1174  // Print times for each timer, as a map from statistic name to its time.
1175  fout << "Total times: ";
1176  if (compact) {
1177  fout << " {";
1178  size_type outerInd = 0;
1179  for (stat_map_type::const_iterator outerIter = statData.begin();
1180  outerIter != statData.end(); ++outerIter, ++outerInd) {
1181  // Print timer name.
1182  fout << quoteLabelForYaml (outerIter->first) << ": ";
1183  // Print that timer's data.
1184  const std::vector<std::pair<double, double> >& curData = outerIter->second;
1185  fout << "{";
1186  for (size_type innerInd = 0; innerInd < curData.size (); ++innerInd) {
1187  fout << quoteLabelForYaml (statNames[innerInd]) << ": "
1188  << curData[innerInd].first;
1189  if (innerInd + 1 < curData.size ()) {
1190  fout << ", ";
1191  }
1192  }
1193  fout << "}";
1194  if (outerInd + 1 < statData.size ()) {
1195  fout << ", ";
1196  }
1197  }
1198  fout << "}" << endl;
1199  }
1200  else {
1201  fout << endl;
1202  OSTab tab1 (pfout);
1203  size_type outerInd = 0;
1204  for (stat_map_type::const_iterator outerIter = statData.begin();
1205  outerIter != statData.end(); ++outerIter, ++outerInd) {
1206  // Print timer name.
1207  fout << quoteLabelForYaml (outerIter->first) << ": " << endl;
1208  // Print that timer's data.
1209  OSTab tab2 (pfout);
1210  const std::vector<std::pair<double, double> >& curData = outerIter->second;
1211  for (size_type innerInd = 0; innerInd < curData.size (); ++innerInd) {
1212  fout << quoteLabelForYaml (statNames[innerInd]) << ": "
1213  << curData[innerInd].first << endl;
1214  }
1215  }
1216  }
1217 
1218  // Print call counts for each timer, for each statistic name.
1219  fout << "Call counts:";
1220  if (compact) {
1221  fout << " {";
1222  size_type outerInd = 0;
1223  for (stat_map_type::const_iterator outerIter = statData.begin();
1224  outerIter != statData.end(); ++outerIter, ++outerInd) {
1225  // Print timer name.
1226  fout << quoteLabelForYaml (outerIter->first) << ": ";
1227  // Print that timer's data.
1228  const std::vector<std::pair<double, double> >& curData = outerIter->second;
1229  fout << "{";
1230  for (size_type innerInd = 0; innerInd < curData.size (); ++innerInd) {
1231  fout << quoteLabelForYaml (statNames[innerInd]) << ": "
1232  << curData[innerInd].second;
1233  if (innerInd + 1 < curData.size ()) {
1234  fout << ", ";
1235  }
1236  }
1237  fout << "}";
1238  if (outerInd + 1 < statData.size ()) {
1239  fout << ", ";
1240  }
1241  }
1242  fout << "}" << endl;
1243  }
1244  else {
1245  fout << endl;
1246  OSTab tab1 (pfout);
1247  size_type outerInd = 0;
1248  for (stat_map_type::const_iterator outerIter = statData.begin();
1249  outerIter != statData.end(); ++outerIter, ++outerInd) {
1250  // Print timer name.
1251  fout << quoteLabelForYaml (outerIter->first) << ": " << endl;
1252  // Print that timer's data.
1253  OSTab tab2 (pfout);
1254  const std::vector<std::pair<double, double> >& curData = outerIter->second;
1255  for (size_type innerInd = 0; innerInd < curData.size (); ++innerInd) {
1256  fout << quoteLabelForYaml (statNames[innerInd]) << ": "
1257  << curData[innerInd].second << endl;
1258  }
1259  }
1260  }
1261  }
1262 
1263  void TimeMonitor::
1264  summarizeToYaml (std::ostream &out,
1265  const ETimeMonitorYamlFormat yamlStyle,
1266  const std::string& filter)
1267  {
1268  // The default communicator. If Trilinos was built with MPI
1269  // enabled, this should be MPI_COMM_WORLD. Otherwise, this should
1270  // be a "serial" (no MPI, one "process") communicator.
1271  RCP<const Comm<int> > comm = getDefaultComm ();
1272 
1273  summarizeToYaml (comm.ptr (), out, yamlStyle, filter);
1274  }
1275 
1276  // Default value is false. We'll set to true once
1277  // setReportParameters() completes successfully.
1278  bool TimeMonitor::setParams_ = false;
1279 
1280  // We have to declare all of these here in order to avoid linker errors.
1284  bool TimeMonitor::alwaysWriteLocal_ = false;
1285  bool TimeMonitor::writeGlobalStats_ = true;
1286  bool TimeMonitor::writeZeroTimers_ = true;
1287 
1288  void
1290  {
1291  const std::string name ("Report format");
1292  const std::string defaultValue ("Table");
1293  const std::string docString ("Output format for report of timer statistics");
1294  Array<std::string> strings;
1295  Array<std::string> docs;
1297 
1298  strings.push_back ("YAML");
1299  docs.push_back ("YAML (see yaml.org) format");
1300  values.push_back (REPORT_FORMAT_YAML);
1301  strings.push_back ("Table");
1302  docs.push_back ("Tabular format via Teuchos::TableFormat");
1303  values.push_back (REPORT_FORMAT_TABLE);
1304 
1305  setStringToIntegralParameter<ETimeMonitorReportFormat> (name, defaultValue,
1306  docString,
1307  strings (), docs (),
1308  values (), &plist);
1309  }
1310 
1311  void
1313  {
1314  const std::string name ("YAML style");
1315  const std::string defaultValue ("spacious");
1316  const std::string docString ("YAML-specific output format");
1317  Array<std::string> strings;
1318  Array<std::string> docs;
1320 
1321  strings.push_back ("compact");
1322  docs.push_back ("Compact format: use \"flow style\" (see YAML 1.2 spec at "
1323  "yaml.org) for most sequences except the outermost sequence");
1324  values.push_back (YAML_FORMAT_COMPACT);
1325 
1326  strings.push_back ("spacious");
1327  docs.push_back ("Spacious format: avoid flow style");
1329 
1330  setStringToIntegralParameter<ETimeMonitorYamlFormat> (name, defaultValue,
1331  docString,
1332  strings (), docs (),
1333  values (), &plist);
1334  }
1335 
1336  void
1338  {
1339  const std::string name ("How to merge timer sets");
1340  const std::string defaultValue ("Intersection");
1341  const std::string docString ("How to merge differing sets of timers "
1342  "across processes");
1343  Array<std::string> strings;
1344  Array<std::string> docs;
1345  Array<ECounterSetOp> values;
1346 
1347  strings.push_back ("Intersection");
1348  docs.push_back ("Compute intersection of timer sets over processes");
1349  values.push_back (Intersection);
1350  strings.push_back ("Union");
1351  docs.push_back ("Compute union of timer sets over processes");
1352  values.push_back (Union);
1353 
1354  setStringToIntegralParameter<ECounterSetOp> (name, defaultValue, docString,
1355  strings (), docs (), values (),
1356  &plist);
1357  }
1358 
1361  {
1362  // Our implementation favors recomputation over persistent
1363  // storage. That is, we simply recreate the list every time we
1364  // need it.
1365  RCP<ParameterList> plist = parameterList ("TimeMonitor::report");
1366 
1367  const bool alwaysWriteLocal = false;
1368  const bool writeGlobalStats = true;
1369  const bool writeZeroTimers = true;
1370 
1371  setReportFormatParameter (*plist);
1372  setYamlFormatParameter (*plist);
1373  setSetOpParameter (*plist);
1374  plist->set ("alwaysWriteLocal", alwaysWriteLocal,
1375  "Always output local timers' values on Proc 0");
1376  plist->set ("writeGlobalStats", writeGlobalStats, "Always output global "
1377  "statistics, even if there is only one process in the "
1378  "communicator");
1379  plist->set ("writeZeroTimers", writeZeroTimers, "Generate output for "
1380  "timers that have never been called");
1381 
1382  return rcp_const_cast<const ParameterList> (plist);
1383  }
1384 
1385  void
1387  {
1390  ECounterSetOp setOp = Intersection;
1391  bool alwaysWriteLocal = false;
1392  bool writeGlobalStats = true;
1393  bool writeZeroTimers = true;
1394 
1395  if (params.is_null ()) {
1396  // If we've set parameters before, leave their current values.
1397  // Otherwise, set defaults (below).
1398  if (setParams_) {
1399  return;
1400  }
1401  }
1402  else { // params is nonnull. Let's read it!
1403  params->validateParametersAndSetDefaults (*getValidReportParameters ());
1404 
1405  reportFormat = getIntegralValue<ETimeMonitorReportFormat> (*params, "Report format");
1406  yamlStyle = getIntegralValue<ETimeMonitorYamlFormat> (*params, "YAML style");
1407  setOp = getIntegralValue<ECounterSetOp> (*params, "How to merge timer sets");
1408  alwaysWriteLocal = params->get<bool> ("alwaysWriteLocal");
1409  writeGlobalStats = params->get<bool> ("writeGlobalStats");
1410  writeZeroTimers = params->get<bool> ("writeZeroTimers");
1411  }
1412  // Defer setting state until here, to ensure the strong exception
1413  // guarantee for this method (either it throws with no externally
1414  // visible state changes, or it returns normally).
1415  reportFormat_ = reportFormat;
1416  yamlStyle_ = yamlStyle;
1417  setOp_ = setOp;
1418  alwaysWriteLocal_ = alwaysWriteLocal;
1419  writeGlobalStats_ = writeGlobalStats;
1420  writeZeroTimers_ = writeZeroTimers;
1421 
1422  setParams_ = true; // Yay, we successfully set parameters!
1423  }
1424 
1425  void
1427  std::ostream& out,
1428  const std::string& filter,
1429  const RCP<ParameterList>& params)
1430  {
1431  setReportParameters (params);
1432 
1434  summarizeToYaml (comm, out, yamlStyle_, filter);
1435  }
1436  else if (reportFormat_ == REPORT_FORMAT_TABLE) {
1438  writeZeroTimers_, setOp_, filter);
1439  }
1440  else {
1441  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "TimeMonitor::report: "
1442  "Invalid report format. This should never happen; ParameterList "
1443  "validation should have caught this. Please report this bug to the "
1444  "Teuchos developers.");
1445  }
1446  }
1447 
1448  void
1450  std::ostream& out,
1451  const RCP<ParameterList>& params)
1452  {
1453  report (comm, out, "", params);
1454  }
1455 
1456  void
1457  TimeMonitor::report (std::ostream& out,
1458  const std::string& filter,
1459  const RCP<ParameterList>& params)
1460  {
1461  RCP<const Comm<int> > comm = getDefaultComm ();
1462  report (comm.ptr (), out, filter, params);
1463  }
1464 
1465  void
1466  TimeMonitor::report (std::ostream& out,
1467  const RCP<ParameterList>& params)
1468  {
1469  RCP<const Comm<int> > comm = getDefaultComm ();
1470  report (comm.ptr (), out, "", params);
1471  }
1472 
1473 } // namespace Teuchos
void reserve(size_type n)
static bool alwaysWriteLocal_
Whether report() should always report Proc 0&#39;s local timer results.
static void setSetOpParameter(ParameterList &plist)
Add the "How to merge timer sets" parameter to plist.
Array< T > & append(const T &x)
Add a new entry at the end of the array.
static ETimeMonitorYamlFormat yamlStyle_
std::map< std::string, std::vector< std::pair< double, double > > > stat_map_type
Global statistics collected from timer data.
static void setReportFormatParameter(ParameterList &plist)
Add the "Report format" parameter to plist.
void setColumnWidths(const Array< int > &colWidths)
Set the column widths to be used for subsequent rows.
static ECounterSetOp setOp_
Whether report() should use the intersection or union of timers over processes.
const Time & counter() const
Constant access to the instance&#39;s counter reference.
TimeMonitor(Time &timer, bool reset=false)
Constructor: starts the timer.
void writeWholeTable(std::ostream &out, const std::string &tableTitle, const Array< std::string > &columnNames, const Array< TableColumn > &columns) const
~TimeMonitor()
Destructor: stops the timer.
static RCP< Time > lookupCounter(const std::string &name)
Return the first counter with the given name, or null if none.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Macro for throwing an exception with breakpointing to ease debugging.
static void disableTimer(const std::string &name)
Disable the timer with the given name.
static bool writeZeroTimers_
Whether report() should report timers with zero call counts.
void reduce(const Ordinal count, const std::pair< double, int > inBuffer[], std::pair< double, int > inoutBuffer[]) const
Teuchos version of MPI_MINLOC.
std::map< std::string, std::pair< double, int > > timer_map_t
T * get() const
Get the raw C++ pointer to the underlying object.
Concrete serial communicator subclass.
static Teuchos::RCP< const Comm< OrdinalType > > getComm()
Return the default global communicator.
Tabbing class for helping to create formated, indented output for a basic_FancyOStream object...
static RCP< const ParameterList > getValidReportParameters()
Default parameters (with validators) for report().
basic_OSTab< char > OSTab
This structure defines some basic traits for a scalar field type.
Teuchos version of MPI_MAXLOC.
Base interface class for user-defined reduction operations for objects that use value semantics...
static void summarize(Ptr< const Comm< int > > comm, std::ostream &out=std::cout, const bool alwaysWriteLocal=false, const bool writeGlobalStats=true, const bool writeZeroTimers=true, const ECounterSetOp setOp=Intersection, const std::string &filter="")
Print summary statistics for all timers on the given communicator.
void reduce(const Ordinal count, const std::pair< double, int > inBuffer[], std::pair< double, int > inoutBuffer[]) const
void reduce(const Ordinal count, const std::pair< ScalarType, IndexType > inBuffer[], std::pair< ScalarType, IndexType > inoutBuffer[]) const
void start(bool reset=false)
Start the timer, if the timer is enabled (see disable()).
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Deprecated.
A column of TableEntry objects.
double stop()
Stop the timer, if the timer is enabled (see disable()).
std::ostream subclass that performs the magic of indenting data sent to an std::ostream object among ...
Wall-clock timer.
Ptr< T > ptr() const
Get a safer wrapper raw C++ pointer to the underlying object.
int precision() const
Get the precision for writing doubles. Default is 4.
static void computeGlobalTimerStatistics(stat_map_type &statData, std::vector< std::string > &statNames, Ptr< const Comm< int > > comm, const ECounterSetOp setOp=Intersection, const std::string &filter="")
Compute global timer statistics for all timers on the given communicator.
static void summarizeToYaml(Ptr< const Comm< int > > comm, std::ostream &out, const ETimeMonitorYamlFormat yamlStyle, const std::string &filter="")
Like summarize(), but with YAML-format output.
static ETimeMonitorReportFormat reportFormat_
Parameters for the report() class method.
Provides utilities for formatting tabular output.
TEUCHOS_DEPRECATED void reduceAll(const Comm< Ordinal > &comm, const EReductionType reductType, const Packet &send, Packet *globalReduct)
Deprecated .
void mergeCounterNames(const Comm< int > &comm, const Array< std::string > &localNames, Array< std::string > &globalNames, const ECounterSetOp setOp)
Merge counter names over all processors.
A list of parameters of arbitrary type.
std::vector< T >::const_iterator const_iterator
static void setReportParameters(const RCP< ParameterList > &params)
Set parameters for report(). Call only from report().
ETimeMonitorReportFormat
Valid output formats for report().
static std::map< std::string, RCP< Time > > & counters()
The class&#39; array of all counters that were created with getNewCounter().
reference back()
Abstract interface for distributed-memory communication.
basic_FancyOStream< char > FancyOStream
void push_back(const value_type &x)
ETimeMonitorYamlFormat
Valid YAML output formats for report().
bool isRecursiveCall() const
Whether we are currently in a recursive call of the counter.
size_type size() const
Defines basic traits for the scalar field type.
static T zero()
Returns representation of zero for this scalar type.
Scope protection wrapper for Teuchos::Time, with timer reporting functionality.
Smart reference counting pointer class for automatic garbage collection.
static bool setParams_
Whether setReportParameters() completed successfully.
ECounterSetOp
Set operation type for mergeCounterNames() to perform.
Common capabilities for collecting and reporting performance data across processors.
iterator begin()
static void setYamlFormatParameter(ParameterList &plist)
Add the "YAML style" parameter to plist.
Simple wrapper class for raw pointers to single objects where no persisting relationship exists...
static void enableTimer(const std::string &name)
Enable the timer with the given name.
static TableFormat & format()
Table format that will be used to print a summary of timer results.
static void zeroOutTimers()
Reset all global timers to zero.
static void report(Ptr< const Comm< int > > comm, std::ostream &out, const std::string &filter, const RCP< ParameterList > &params=null)
Report timer statistics to the given output stream.
bool is_null() const
Returns true if the underlying pointer is null.