Imported Upstream version 1.12.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 EventCollector::Event &evt_collected, const std::string &ph) const
42   {
43     DurationEvent evt;
44
45     evt.name = evt_collected.label;
46     evt.tid = evt_collected.backend;
47     evt.ph = ph;
48     evt.ts = _ts;
49
50     evt.args = evt_collected.userData;
51
52     return evt;
53   }
54
55 private:
56   std::string _ts;
57 };
58
59 #ifdef DEBUG
60 inline void emit_rusage(EventRecorder *rec, const std::string &ts)
61 {
62   struct rusage ru;
63
64   getrusage(RUSAGE_SELF, &ru);
65   {
66     CounterEvent evt;
67
68     evt.name = "maxrss";
69     evt.ph = "C";
70     evt.ts = ts;
71     evt.values["value"] = std::to_string(ru.ru_maxrss);
72
73     rec->emit(evt);
74   }
75
76   {
77     CounterEvent evt;
78
79     evt.name = "minflt";
80     evt.ph = "C";
81     evt.ts = ts;
82     evt.values["value"] = std::to_string(ru.ru_minflt);
83
84     rec->emit(evt);
85   }
86 }
87 #endif
88
89 } // namespace
90
91 void EventCollector::onEvent(const Event &event)
92 {
93   auto ts = timestamp();
94
95   switch (event.edge)
96   {
97     case Edge::BEGIN:
98       _rec->emit(DurationEventBuilder(ts).build(event, "B"));
99       break;
100
101     case Edge::END:
102       _rec->emit(DurationEventBuilder(ts).build(event, "E"));
103       break;
104   }
105
106 // TODO: Add resurece measurement(e.g. RSS)
107 // when ready with low overhead in release build
108 #ifdef DEBUG
109   emit_rusage(_rec, ts);
110 #endif
111 }