Stat.h 8.0 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

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 <sys/time.h>
#include <iostream>
L
liaogang 已提交
20 21
#include <list>
#include <memory>
Z
zhangjinchao01 已提交
22
#include <mutex>
L
liaogang 已提交
23
#include <string>
Z
zhangjinchao01 已提交
24 25 26 27
#include <unordered_map>

#include "BarrierStat.h"
#include "Locks.h"
L
liaogang 已提交
28
#include "Logging.h"
Z
zhangjinchao01 已提交
29
#include "ThreadLocal.h"
L
liaogang 已提交
30
#include "hl_gpu.h"
Z
zhangjinchao01 已提交
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

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;
  }

96 97
  BarrierStatPtr getStat(uint16_t numConnThreads,
                         const std::string& name,
Z
zhangjinchao01 已提交
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
                         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:
208 209 210 211
  TimerOnce(Stat* stat,
            const char* info = "",
            uint64_t threshold = -1,
            bool autoStart = true,
Z
zhangjinchao01 已提交
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
            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); \
267 268
  TimerOnce __timerOnce(                                                    \
      __stat.get(), "", registerTimerArg1(__VA_ARGS__), false, start);
Z
zhangjinchao01 已提交
269 270

// dynmaic timer, support to discriminate runtime entity, used in pserver
271 272
#define REGISTER_TIMER_DYNAMIC(statName, ...)                        \
  StatPtr __stat = registerTimerArg2(__VA_ARGS__).getStat(statName); \
Z
zhangjinchao01 已提交
273 274
  TimerOnce __timerOnce(__stat.get(), "", registerTimerArg1(__VA_ARGS__));

275 276 277 278
#define REGISTER_TIMER_DYNAMIC_SET(statName, start, ...)             \
  StatPtr __stat = registerTimerArg2(__VA_ARGS__).getStat(statName); \
  TimerOnce __timerOnce(                                             \
      __stat.get(), "", registerTimerArg1(__VA_ARGS__), false, start);
Z
zhangjinchao01 已提交
279

280 281
#define REGISTER_TIMER_INFO(statName, info)             \
  static StatPtr __stat = globalStat.getStat(statName); \
Z
zhangjinchao01 已提交
282 283 284 285
  TimerOnce __timerOnce(__stat.get(), info, 10 * 1000000LU /*threshold*/);

#endif  // DISABLE_TIMER

L
liaogang 已提交
286 287
class GpuProfiler final {
public:
288 289
  GpuProfiler(std::string statName, std::string info);
  ~GpuProfiler();
L
liaogang 已提交
290

291 292
private:
  std::lock_guard<std::recursive_mutex> guard_;
L
liaogang 已提交
293 294 295 296 297 298 299 300
};

#ifdef PADDLE_DISABLE_PROFILER

#define REGISTER_GPU_PROFILER(statName, ...)

#else

301 302
#define REGISTER_GPU_PROFILER(statName, ...) \
  GpuProfiler __gpuProfiler(statName, #__VA_ARGS__);
L
liaogang 已提交
303 304 305

#endif  // DISABLE_PROFILER

Z
zhangjinchao01 已提交
306
}  // namespace paddle