basic_profiler.h 9.7 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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.

/*
 * This file implements BasicProfile, a profiler that helps to profile the basic
 * CPU execution. It can display the min, max, average lantency of the execution
 * of each kernel.
 */
#pragma once
21
#include <gflags/gflags.h>
Y
Yan Chunwei 已提交
22 23 24
#include <time.h>
#include <algorithm>
#include <chrono>  // NOLINT
25
#include <fstream>
Y
Yan Chunwei 已提交
26
#include <limits>
27
#include <map>
Y
Yan Chunwei 已提交
28 29 30 31 32 33 34 35 36 37 38
#include <memory>
#include <string>
#include <vector>
#include "lite/utils/cp_logging.h"
#include "lite/utils/replace_stl/stream.h"
#include "lite/utils/string.h"

namespace paddle {
namespace lite {
namespace profile {

39 40 41 42 43 44 45 46 47 48 49 50 51 52
struct TimerInfo {
  uint64_t total_{};
  uint64_t count_{};
  uint32_t max_{std::numeric_limits<uint32_t>::min()};
  uint32_t min_{std::numeric_limits<uint32_t>::max()};
  uint64_t timer_{};

  double ave() const { return total_ * 1. / count_; }
  double max() const { return max_; }
  double min() const { return min_; }
  uint64_t total() const { return total_; }
  uint64_t count() const { return count_; }
};

Y
Yan Chunwei 已提交
53 54 55 56
/* Base class of all the profile records */
template <typename ChildT>
class TimerBase {
 public:
57 58 59 60 61
  void Start(const std::string& key) { self()->Start(key); }
  void Stop(const std::string& key) { self()->Stop(key); }
  void Log(TimerInfo* timer_info, uint32_t x) {
    return self()->Log(timer_info, x);
  }
Y
Yan Chunwei 已提交
62 63 64
  std::string basic_repr() const { return const_self()->basic_repr(); }

  void SetId(int id) { self()->SetId(id); }
65
  void SetKey(const std::string& key) { self()->SetKey(key); }
Y
Yan Chunwei 已提交
66 67 68 69

  int id() const { return const_self()->id(); }

 protected:
70 71 72
  ChildT* self() { return reinterpret_cast<ChildT*>(this); }
  const ChildT* const_self() const {
    return reinterpret_cast<const ChildT*>(this);
Y
Yan Chunwei 已提交
73 74 75 76 77 78
  }
};

class BasicTimer : TimerBase<BasicTimer> {
  int id_{-1};
  std::string key_;
79 80
  std::map<std::string, TimerInfo> timer_infos_;
  std::map<std::string, std::string> custom_infos_;
Y
Yan Chunwei 已提交
81 82 83 84 85 86 87

  // TODO(Superjomn) make static
  static const int name_w;
  static const int data_w;

 public:
  BasicTimer() = default;
88
  BasicTimer(int id, const std::string& key) : id_(id), key_(key) {}
Y
Yan Chunwei 已提交
89 90

  void SetId(int id) { id_ = id; }
91 92 93 94
  void SetKey(const std::string& key) { key_ = key; }
  void Start(const std::string& timer_key) {
    TimerInfo& timer_info = timer_infos_[timer_key];
    timer_info.timer_ = static_cast<uint64_t>(
95 96 97 98
        std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::system_clock::now().time_since_epoch())
            .count());
  }
99 100 101 102 103 104
  void Stop(const std::string& timer_key) {
    if (timer_infos_.find(timer_key) == timer_infos_.end()) {
      LOG(FATAL) << "Error: Can't found timer key [" << timer_key << "] for "
                 << key_;
    }
    TimerInfo& timer_info = timer_infos_[timer_key];
105 106 107 108 109
    auto duration = static_cast<
        uint64_t>(  // timer unit: microsecond, 1second = 1e6 microsecond
        std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::system_clock::now().time_since_epoch())
            .count() -
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        timer_info.timer_);
    Log(&timer_info, duration);
  }

  void SetCustomInfo(const std::string& key, const std::string& value) {
    if (custom_infos_.find(key) != custom_infos_.end()) {
      LOG(FATAL) << "Error: Custom Info for key [" << key
                 << "] can't be overwritten";
    }
    custom_infos_[key] = value;
  }

  std::string GetCustomInfo(const std::string& key) const {
    auto iter = custom_infos_.find(key);
    if (iter == custom_infos_.end()) {
      LOG(FATAL) << "Error: Custom Info for key [" << key << "] can't be found";
    }
    return iter->second;
Y
Yan Chunwei 已提交
128 129
  }

130 131 132 133 134 135 136
  const TimerInfo& GetTimerInfo(const std::string& key) const {
    auto iter = timer_infos_.find(key);
    if (iter == timer_infos_.end()) {
      LOG(FATAL) << "Error: Timer Info for key [" << key << "] can't be found";
    }
    return iter->second;
  }
Y
Yan Chunwei 已提交
137

138 139 140 141 142 143
  void Log(TimerInfo* timer_info, uint32_t timespan) {
    CHECK(timer_info);
    timer_info->total_ += timespan;
    timer_info->max_ = std::max(timer_info->max_, timespan);
    timer_info->min_ = std::min(timer_info->min_, timespan);
    timer_info->count_++;
Y
Yan Chunwei 已提交
144 145 146 147
  }

  static std::string basic_repr_header() {
    STL::stringstream ss;
148 149 150 151 152 153 154 155 156 157 158 159
    // clang-format off
    ss << "op"        << "\t"
       << "kernel"    << "\t"
       << "k_average" << "\t"
       << "k_min"     << "\t"
       << "k_max"     << "\t"
       << "i_average" << "\t"
       << "i_min"     << "\t"
       << "i_max"     << "\t"
       << "count"     << "\t"
       << "op_info";
    // clang-format on
Y
Yan Chunwei 已提交
160 161 162 163
    return ss.str();
  }

  std::string basic_repr() const {
164 165
    auto& kernel_timer_info = GetTimerInfo("kernel");
    auto& inst_timer_info = GetTimerInfo("instruction");
Y
Yan Chunwei 已提交
166
    STL::stringstream ss;
167 168 169 170 171 172 173 174 175 176 177 178
    // clang-format off
    ss << GetCustomInfo("op_type") << "\t"
       << key()                    << "\t"
       << kernel_timer_info.ave()  << "\t"
       << kernel_timer_info.min()  << "\t"
       << kernel_timer_info.max()  << "\t"
       << inst_timer_info.ave()    << "\t"
       << inst_timer_info.min()    << "\t"
       << inst_timer_info.max()    << "\t"
       << inst_timer_info.count()  << "\t"
       << GetCustomInfo("op_info");
    // clang-format on
Y
Yan Chunwei 已提交
179 180 181
    return ss.str();
  }

182
  const std::string& key() const { return key_; }
Y
Yan Chunwei 已提交
183 184 185 186 187 188 189

  int id() const {
    CHECK_GE(id_, 0) << "id is not inited";
    return id_;
  }

  // BasicRecord(const BasicRecord &) = delete;
190
  void operator=(const BasicTimer&) = delete;
Y
Yan Chunwei 已提交
191 192 193 194 195 196 197 198
};

/*
 * A basic profiler, with each record logs the total latency.
 */
template <typename TimerT>
class BasicProfiler {
 public:
199
  explicit BasicProfiler(const std::string& name) : name_(name) {}
Y
Yan Chunwei 已提交
200 201
  using record_t = TimerT;

202
  static BasicProfiler& Global() {
Y
Yan Chunwei 已提交
203 204 205 206
    static std::unique_ptr<BasicProfiler> x(new BasicProfiler("[global]"));
    return *x;
  }

207
  record_t& NewRcd(const std::string& key) {
Y
Yan Chunwei 已提交
208 209 210 211 212 213
    records_.emplace_back();
    records_.back().SetId(records_.size() - 1);
    records_.back().SetKey(key);
    return records_.back();
  }

214
  const record_t& record(int id) {
Y
Yan Chunwei 已提交
215 216 217 218 219
    CHECK_LT(id, records_.size());
    CHECK_GE(id, 0);
    return records_[id];
  }

220
  record_t* mutable_record(int id) {
Y
Yan Chunwei 已提交
221 222 223 224 225 226 227
    CHECK_GE(id, 0);
    CHECK_LT(static_cast<size_t>(id), records_.size());
    return &records_[id];
  }

  std::string basic_repr() const {
    STL::stringstream ss;
228
    for (const auto& rcd : records_) {
Y
Yan Chunwei 已提交
229 230 231 232 233
      ss << rcd.basic_repr() << "\n";
    }
    return ss.str();
  }

234 235 236 237 238 239 240 241 242 243 244 245 246
  std::string summary_repr_header() const {
    STL::stringstream ss;
    // clang-format off
    ss << "op"         << "\t"
       << "average"    << "\t"
       << "min"        << "\t"
       << "max"        << "\t"
       << "op_time"    << "\t"
       << "total_time" << "\t"
       << "precent"    << "\t"
       << "count";
    // clang-format on
    return ss.str();
Y
Yan Chunwei 已提交
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 284 285
  std::string summary_repr() const {
    std::map<std::string, TimerInfo> op_summary;
    uint64_t total{0};

    for (const auto& rcd : records_) {
      // We use kernel run time here
      auto kernel_timer = rcd.GetTimerInfo("kernel");
      auto op_type = rcd.GetCustomInfo("op_type");
      auto& op_timer = op_summary[op_type];

      total += kernel_timer.total_;
      op_timer.total_ += kernel_timer.total_;
      op_timer.max_ = std::max(kernel_timer.max_, op_timer.max_);
      op_timer.min_ = std::min(kernel_timer.min_, op_timer.min_);
      op_timer.count_ += kernel_timer.count_;
    }

    STL::stringstream ss;
    for (auto& iter : op_summary) {
      auto& op_timer = iter.second;
      // clang-format off
      ss << iter.first                             << "\t"
         << op_timer.ave()                         << "\t"
         << op_timer.min()                         << "\t"
         << op_timer.max()                         << "\t"
         << op_timer.total()                       << "\t"
         << total                                  << "\t"
         << (op_timer.total() * 1. / total * 100)  << "%\t"
         << op_timer.count()                       << "\t"
         << "\n";
      // clang-format on
    }
    return ss.str();
  }

  ~BasicProfiler();

Y
Yan Chunwei 已提交
286 287 288 289 290 291
 private:
  std::string name_;
  std::vector<record_t> records_;
};

struct ProfileBlock {
292 293 294 295 296 297 298 299 300 301
  explicit ProfileBlock(int id, const std::string& key) : id_(id), key_(key) {
    BasicProfiler<BasicTimer>::Global().mutable_record(id_)->Start(key_);
  }

  void Record() {
    if (has_recorded_) {
      LOG(FATAL) << "You can only call Record() once";
    }
    BasicProfiler<BasicTimer>::Global().mutable_record(id_)->Stop(key_);
    has_recorded_ = true;
Y
Yan Chunwei 已提交
302 303 304
  }

  ~ProfileBlock() {
305 306 307
    if (!has_recorded_) {
      BasicProfiler<BasicTimer>::Global().mutable_record(id_)->Stop(key_);
    }
Y
Yan Chunwei 已提交
308 309 310 311
  }

 private:
  int id_{};
312 313
  bool has_recorded_{false};
  std::string key_{};
Y
Yan Chunwei 已提交
314 315
};

316 317 318 319 320 321 322 323
#define LITE_PROFILE_ONE(key__)                            \
  static int key__##__profiler_id =                        \
      ::paddle::lite::profile::BasicProfiler<              \
          ::paddle::lite::profile::BasicTimer>::Global()   \
          .NewRcd(#key__)                                  \
          .id();                                           \
  ::paddle::lite::profile::ProfileBlock key__##profiler__( \
      key__##__profiler_id, #key__);
Y
Yan Chunwei 已提交
324 325 326 327

}  // namespace profile
}  // namespace lite
}  // namespace paddle