Stat.h 8.5 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
#include <unordered_map>

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

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;

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

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

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

  // 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_;
  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:
191 192 193 194
  TimerOnce(Stat* stat,
            const char* info = "",
            uint64_t threshold = -1,
            bool autoStart = true,
Z
zhangjinchao01 已提交
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
            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
X
xuwei06 已提交
244 245 246 247 248
#define REGISTER_TIMER(statName, ...)                             \
  static ::paddle::StatPtr __stat =                               \
      ::paddle::registerTimerArg2(__VA_ARGS__).getStat(statName); \
  ::paddle::TimerOnce __timerOnce(                                \
      __stat.get(), "", ::paddle::registerTimerArg1(__VA_ARGS__));
Z
zhangjinchao01 已提交
249 250

#define REGISTER_TIMER_SET(statName, start, ...)                            \
X
xuwei06 已提交
251 252 253 254 255 256 257
  static ::paddle::StatPtr __stat =                                         \
      ::paddle::registerTimerArg2(__VA_ARGS__).getStat(statName);           \
  ::paddle::TimerOnce __timerOnce(__stat.get(),                             \
                                  "",                                       \
                                  ::paddle::registerTimerArg1(__VA_ARGS__), \
                                  false,                                    \
                                  start);
Z
zhangjinchao01 已提交
258 259

// dynmaic timer, support to discriminate runtime entity, used in pserver
X
xuwei06 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
#define REGISTER_TIMER_DYNAMIC(statName, ...)                     \
  ::paddle::StatPtr __stat =                                      \
      ::paddle::registerTimerArg2(__VA_ARGS__).getStat(statName); \
  ::paddle::TimerOnce __timerOnce(                                \
      __stat.get(), "", ::paddle::registerTimerArg1(__VA_ARGS__));

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

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

#endif  // DISABLE_TIMER

L
liaogang 已提交
282 283
class GpuProfiler final {
public:
284 285
  GpuProfiler(std::string statName, std::string info);
  ~GpuProfiler();
L
liaogang 已提交
286

287 288
private:
  std::lock_guard<std::recursive_mutex> guard_;
L
liaogang 已提交
289 290 291 292 293 294 295 296
};

#ifdef PADDLE_DISABLE_PROFILER

#define REGISTER_GPU_PROFILER(statName, ...)

#else

297 298
#define REGISTER_GPU_PROFILER(statName, ...) \
  GpuProfiler __gpuProfiler(statName, #__VA_ARGS__);
L
liaogang 已提交
299 300 301

#endif  // DISABLE_PROFILER

Z
zhangjinchao01 已提交
302
}  // namespace paddle