1. #ifndef __TIMER_HPP__
  2. #define __TIMER_HPP__
  3.  
  4. #include <sys/time.h>
  5. #include <cstdlib>
  6. #include <mpi.h>
  7. #include <Datatypes.hpp>
  8. #include <string>
  9. #include <iomanip>
  10. #include <map>
  11.  
  12. class Timer {
  13. public:
  14.     Timer() : time_(0.0) {}
  15.     ~Timer() { }
  16.  
  17.     void start() {
  18.         gettimeofday(&start_, 0);
  19.     }
  20.  
  21.     void stop() {
  22.         gettimeofday(&stop_, 0);
  23.         time_ += ((stop_.tv_sec*1000000+stop_.tv_usec)-(start_.tv_sec*1000000+start_.tv_usec))/1000000.00;
  24.     }
  25.  
  26.     void reduce(const Subdomain& subdomain) {
  27.         MPI_Allreduce(&time_, &timeTotal_, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
  28.         MPI_Allreduce(&time_, &timeMin_, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);
  29.         MPI_Allreduce(&time_, &timeMax_, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
  30.  
  31.         timeTotal_ /= subdomain.numProcs;
  32.  
  33.     }
  34.  
  35.     double getTime() { return time_; }
  36.  
  37.     friend std::ostream& operator<<(std::ostream& os, const Timer& t);
  38.  
  39. private:
  40.     double time_, timeTotal_, timeMin_, timeMax_;
  41.     timeval start_, stop_;
  42. };
  43.  
  44. std::ostream& operator<<(std::ostream& os, const Timer& t) {
  45.     return os << std::scientific << std::setw(8)  << std::setprecision(3)
  46.                 << t.timeTotal_ << " \t " << t.timeMin_ << " \t " << t.timeMax_;
  47. }
  48.  
  49.  
  50. class TimeMap {
  51. public:
  52.     TimeMap() { }
  53.     ~TimeMap() { }
  54.  
  55.     void reduce(const Subdomain& subdomain) {
  56.         for(std::map<std::string, Timer>::iterator it = map_.begin(); it != map_.end(); ++it)
  57.             it->second.reduce(subdomain);
  58.     }
  59.  
  60.     double getTotalTime() {
  61.         double ret = 0.0;
  62.         for(std::map<std::string, Timer>::iterator it = map_.begin(); it != map_.end(); ++it)
  63.             ret += it->second.getTime();
  64.  
  65.         return ret;
  66.     }
  67.  
  68.     Timer& operator[](const std::string& name) {
  69.         return map_[name];
  70.     }
  71.  
  72.     friend std::ostream& operator<<(std::ostream& os, const TimeMap& t);
  73. private:
  74.     std::map<std::string, Timer> map_;
  75.  
  76. };
  77.  
  78. std::ostream& operator<<(std::ostream& os, const TimeMap& t) {
  79.     for(std::map<std::string, Timer>::const_iterator it = t.map_.begin(); it != t.map_.end(); ++it) {
  80.         os  << "--- " << std::setw(15) << std::left << it->first << "\t" << it->second << "\n";
  81.     }
  82.     return os << "--------------\n";
  83. }
  84.  
  85. #endif // __TIMER_HPP__