Stat.h 7.6 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once

#include <stdint.h>
#include <string>
#include <sys/time.h>
#include <memory>
#include <iostream>
#include <mutex>
#include <unordered_map>
#include <list>

#include "Logging.h"
#include "BarrierStat.h"
#include "Locks.h"
#include "ThreadLocal.h"
#include "BarrierStat.h"

namespace paddle {

class Stat;

class StatInfo {
public:
  explicit StatInfo(Stat* stat = nullptr) : stat_(stat) {
    total_ = 0;
    max_ = 0;
    count_ = 0;
    min_ = UINT64_MAX;
  }

  void reset() {
    total_ = 0;
    count_ = 0;
    max_ = 0;
    min_ = UINT64_MAX;
  }

  ~StatInfo();

  Stat* stat_;
  uint64_t total_;
  uint64_t max_;
  uint64_t count_;
  uint64_t min_;
};

class Stat;
typedef std::shared_ptr<Stat> StatPtr;
typedef std::shared_ptr<BarrierStatBase> BarrierStatPtr;

enum BarrierStatType {
  BARRIER_END = 0,
  BARRIER_DELTA = 1,
};

class StatSet {
public:
  explicit StatSet(const std::string& name) : name_(name) {}
  ~StatSet() {}

  // print to LOG(INFO)
  void printSegTimerStatus();
  void printBarrierTimerStatus();
  void printAllStatus();

  void printStatus(const std::string& name);

  StatPtr getStat(const std::string& name) {
    {
      ReadLockGuard guard(lock_);
      auto it = statSet_.find(name);
      if (it != statSet_.end()) {
        return it->second;
      }
    }
    StatPtr stat = std::make_shared<Stat>(name);
    std::lock_guard<RWLock> guard(lock_);
    auto ret = statSet_.insert(std::make_pair(name, stat));
    return ret.first->second;
  }

  BarrierStatPtr getStat(uint16_t numConnThreads, const std::string& name,
                         BarrierStatType bType);

  void deleteStat(const std::string& name);

  // true for showing stats for each thread
  // false for showing stats aggragated over threads
  void setThreadInfo(const std::string& name, bool flag);

  // true for showing stats for each thread
  // false for showing stats aggragated over threads
  void setThreadInfo(bool flag) {
    for (auto& iter : statSet_) {
      setThreadInfo(iter.first, flag);
    }
  }

  // reset the counters for all stats
  // clearRawData means also clearing raw tuning data, because at pserver end,
  // barrier rawData(timeVector_) is stateful, clearing it will cause rubbish
  // data, while rawData should be cleared at the new pass (so complicated
  // pserver code logic, -_- ).
  void reset(bool clearRawData = true);

private:
  std::unordered_map<std::string, StatPtr> statSet_;
  std::unordered_map<std::string, BarrierStatPtr> barrierStatSet_;
  const std::string name_;
  RWLock lock_;
};

extern StatSet globalStat;

/*@brief : a simple stat*/
class Stat {
public:
  explicit Stat(const std::string& statName)
      : destructStat_(nullptr), name_(statName), openThreadInfo_(false) {}
  ~Stat() {}

  typedef std::list<std::pair<StatInfo*, pid_t>> ThreadLocalBuf;

  const std::string& getName() const { return name_; }

  void addSample(uint64_t value);

  // clear all stats
  void reset();

  friend std::ostream& operator<<(std::ostream& outPut, const Stat& stat);

  /*  Set operator << whether to print thread info.
   *  If openThreadInfo_ == true, then print, else print merge thread info.
   */
  void setThreadInfo(bool flag) { openThreadInfo_ = flag; }

  bool getThreadInfo() const { return openThreadInfo_; }

  friend class StatInfo;

private:
  void mergeThreadStat(StatInfo& allThreadStat);

  std::mutex lock_;
  ThreadLocalBuf threadLocalBuf_;
  StatInfo destructStat_;
  ThreadLocal<StatInfo> statInfo_;
  const std::string name_;
  bool openThreadInfo_;
};

extern StatSet globalStat;

inline StatPtr getStat(const std::string& name) {
  return globalStat.getStat(name);
}

inline uint64_t nowInMicroSec() {
  timeval tvTime;
  (void)gettimeofday(&tvTime, NULL);
  return tvTime.tv_sec * 1000000LU + tvTime.tv_usec;
}

/**
 * A simple help class to measure time interval
 */
class Timer {
public:
  explicit Timer(bool autoStart = true) : total_(0), startStamp_(0) {
    if (autoStart) {
      start();
    }
  }
  void start() { startStamp_ = nowInMicroSec(); }
  void setStartStamp(uint64_t startStamp) { startStamp_ = startStamp; }
  uint64_t stop() {
    total_ += nowInMicroSec() - startStamp_;
    return total_;
  }

  uint64_t get() const { return total_; }

  void reset() { total_ = 0; }

protected:
  uint64_t total_;
  uint64_t startStamp_;
};

class TimerOnce {
public:
  TimerOnce(Stat* stat, const char* info = "",
            uint64_t threshold = -1, bool autoStart = true,
            uint64_t startStamp = 0)
      : stat_(stat), info_(info), timer_(autoStart), threshold_(threshold) {
    if (!autoStart) {
      timer_.setStartStamp(startStamp);
    }
  }
  ~TimerOnce() {
    uint64_t span = timer_.stop();
    if (span >= threshold_) {
      LOG(INFO) << "Stat: [" << stat_->getName() << "] " << info_
                << " [Span:" << span / 1000 << "ms" << span % 1000 << "us"
                << "] ";
    }
    stat_->addSample(span);
  }

private:
  Stat* stat_;
  const char* info_;
  Timer timer_;
  uint64_t threshold_;
};

inline uint64_t registerTimerArg1(uint64_t threshold = -1,
                                  StatSet& statSet = globalStat) {
  return threshold;
}

inline StatSet& registerTimerArg2(uint64_t threshold = -1,
                                  StatSet& statSet = globalStat) {
  return statSet;
}

#ifdef PADDLE_DISABLE_TIMER

#define REGISTER_TIMER(statName, ...)
#define REGISTER_TIMER_SET(statName, start, ...)
#define REGISTER_TIMER_DYNAMIC(statName, ...)
#define REGISTER_TIMER_DYNAMIC_SET(statName, start, ...)
#define REGISTER_TIMER_INFO(statName, info)
#define FOR_TIMING(statement)

#else

#define FOR_TIMING(statement) statement

// The default arguments are shown in the following line:
// REGISTER_TIMER(statName, threshold = -1, statSet = globalStat)
// TODO(yuyang18,wangyanfei01): if UNIQUE_NAME is needed
#define REGISTER_TIMER(statName, ...)                                       \
  static StatPtr __stat = registerTimerArg2(__VA_ARGS__).getStat(statName); \
  TimerOnce __timerOnce(__stat.get(), "", registerTimerArg1(__VA_ARGS__));

#define REGISTER_TIMER_SET(statName, start, ...)                            \
  static StatPtr __stat = registerTimerArg2(__VA_ARGS__).getStat(statName); \
  TimerOnce __timerOnce(__stat.get(), "", registerTimerArg1(__VA_ARGS__),   \
                        false, start);

// dynmaic timer, support to discriminate runtime entity, used in pserver
#define REGISTER_TIMER_DYNAMIC(statName, ...)                               \
  StatPtr __stat = registerTimerArg2(__VA_ARGS__).getStat(statName);        \
  TimerOnce __timerOnce(__stat.get(), "", registerTimerArg1(__VA_ARGS__));

#define REGISTER_TIMER_DYNAMIC_SET(statName, start, ...)                    \
  StatPtr __stat = registerTimerArg2(__VA_ARGS__).getStat(statName);        \
  TimerOnce __timerOnce(__stat.get(), "", registerTimerArg1(__VA_ARGS__),   \
                        false, start);

#define REGISTER_TIMER_INFO(statName, info)                                 \
  static StatPtr __stat = globalStat.getStat(statName);                     \
  TimerOnce __timerOnce(__stat.get(), info, 10 * 1000000LU /*threshold*/);

#endif  // DISABLE_TIMER

}  // namespace paddle