Imported Upstream version 1.8.0
[platform/core/ml/nnfw.git] / runtime / onert / core / src / util / EventCollector.cc
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "util/EventCollector.h"
18
19 // C++ standard libraries
20 #include <chrono>
21
22 // POSIX standard libraries
23 #include <sys/time.h>
24 #include <sys/resource.h>
25
26 namespace
27 {
28
29 std::string timestamp(void)
30 {
31   auto now = std::chrono::steady_clock::now();
32   return std::to_string(
33       std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count());
34 }
35
36 class DurationEventBuilder
37 {
38 public:
39   DurationEventBuilder(const std::string &ts) : _ts{ts} {}
40
41   DurationEvent build(const std::string &tid, const std::string &name, const std::string &ph) const
42   {
43     DurationEvent evt;
44
45     evt.name = name;
46     evt.tid = tid;
47     evt.ph = ph;
48     evt.ts = _ts;
49
50     return evt;
51   }
52
53 private:
54   std::string _ts;
55 };
56
57 #ifdef DEBUG
58 inline void emit_rusage(EventRecorder *rec, const std::string &ts)
59 {
60   struct rusage ru;
61
62   getrusage(RUSAGE_SELF, &ru);
63   {
64     CounterEvent evt;
65
66     evt.name = "maxrss";
67     evt.ph = "C";
68     evt.ts = ts;
69     evt.values["value"] = std::to_string(ru.ru_maxrss);
70
71     rec->emit(evt);
72   }
73
74   {
75     CounterEvent evt;
76
77     evt.name = "minflt";
78     evt.ph = "C";
79     evt.ts = ts;
80     evt.values["value"] = std::to_string(ru.ru_minflt);
81
82     rec->emit(evt);
83   }
84 }
85 #endif
86
87 } // namespace
88
89 void EventCollector::onEvent(const Event &event)
90 {
91   auto ts = timestamp();
92
93   switch (event.edge)
94   {
95     case Edge::BEGIN:
96       _rec->emit(DurationEventBuilder(ts).build(event.backend, event.label, "B"));
97       break;
98
99     case Edge::END:
100       _rec->emit(DurationEventBuilder(ts).build(event.backend, event.label, "E"));
101       break;
102   }
103
104 // TODO: Add resurece measurement(e.g. RSS)
105 // when ready with low overhead in release build
106 #ifdef DEBUG
107   emit_rusage(_rec, ts);
108 #endif
109 }