Caffe2 - C++ API
A deep learning, cross platform ML framework
time_observer.h
1 
17 #ifndef CAFFE2_CONTRIB_OBSERVERS_TIME_OBSERVER_H_
18 #define CAFFE2_CONTRIB_OBSERVERS_TIME_OBSERVER_H_
19 
20 #include <unordered_map>
21 
22 #include "caffe2/core/common.h"
23 #include "caffe2/core/net.h"
24 #include "caffe2/core/observer.h"
25 #include "caffe2/core/operator.h"
26 #include "caffe2/core/timer.h"
27 #include "caffe2/observers/operator_attaching_net_observer.h"
28 
29 namespace caffe2 {
30 
31 class TimeObserver;
32 class TimeCounter {
33  public:
34  explicit TimeCounter() {}
35  inline float average_time() const {
36  return total_time_ / iterations_;
37  }
38 
39  protected:
40  Timer timer_;
41  float start_time_ = 0.0f;
42  float total_time_ = 0.0f;
43  int iterations_ = 0;
44 };
45 
46 class TimeOperatorObserver final : public TimeCounter,
47  public ObserverBase<OperatorBase> {
48  public:
49  explicit TimeOperatorObserver(OperatorBase* subject) = delete;
50  explicit TimeOperatorObserver(
51  OperatorBase* subject,
52  TimeObserver* /* unused */)
53  : ObserverBase<OperatorBase>(subject) {}
54 
55  std::unique_ptr<ObserverBase<OperatorBase>> copy(
56  OperatorBase* subject) override {
57  return std::unique_ptr<ObserverBase<OperatorBase>>(
58  new TimeOperatorObserver(subject, nullptr));
59  }
60 
61  private:
62  void Start() override;
63  void Stop() override;
64 };
65 
66 class TimeObserver final
67  : public TimeCounter,
68  public OperatorAttachingNetObserver<TimeOperatorObserver, TimeObserver> {
69  public:
70  explicit TimeObserver(NetBase* subject)
72  subject,
73  this) {}
74 
75  float average_time_children() const {
76  float sum = 0.0f;
77  for (const auto* observer : operator_observers_) {
78  sum += observer->average_time();
79  }
80  return sum / subject_->GetOperators().size();
81  }
82 
83  private:
84  void Start() override;
85  void Stop() override;
86 };
87 
88 } // namespace caffe2
89 
90 #endif // CAFFE2_CONTRIB_OBSERVERS_TIME_OBSERVER_H_
Use this to implement a Observer using the Observer Pattern template.
Definition: observer.h:30
Copyright (c) 2016-present, Facebook, Inc.
A simple timer object for measuring time.
Definition: timer.h:32