Imported Upstream version 1.7.0
[platform/core/ml/nnfw.git] / runtime / onert / core / src / util / EventCollectorGlobal.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/EventCollectorGlobal.h"
18
19 #include <cassert>
20 #include <fstream>
21 #include <iostream>
22
23 #include "util/ConfigSource.h"
24
25 namespace onert
26 {
27 namespace util
28 {
29
30 EventCollectorGlobal::EventCollectorGlobal() : _recorder{}, _collector{&_recorder}
31 {
32   // DO NOTHING
33 }
34
35 EventCollectorGlobal::~EventCollectorGlobal()
36 {
37   if (!_recorder.empty())
38   {
39     try
40     {
41       // TODO Need better way for saved file path than the hardcoded path
42       std::ofstream ofs{"trace.global.json"};
43       _recorder.writeToFile(ofs);
44     }
45     catch (const std::exception &e)
46     {
47       std::cerr << "E: Fail to record event in EventCollectorGlobal: " << e.what() << std::endl;
48     }
49   }
50 }
51
52 EventCollectorGlobal &EventCollectorGlobal::get()
53 {
54   static EventCollectorGlobal instance;
55   return instance;
56 }
57
58 EventDurationBlock::EventDurationBlock(const std::string &tag) : _tag{tag}
59 {
60   auto &glob = EventCollectorGlobal::get();
61   glob.collector().onEvent(EventCollector::Event{EventCollector::Edge::BEGIN, "0", _tag});
62 }
63 EventDurationBlock::~EventDurationBlock()
64 {
65   auto &glob = EventCollectorGlobal::get();
66   glob.collector().onEvent(EventCollector::Event{EventCollector::Edge::END, "0", _tag});
67 }
68
69 EventDurationManual::EventDurationManual(const std::string &tag) : _tag{tag}, _pair{true} {}
70
71 EventDurationManual::~EventDurationManual()
72 {
73   // Check if it has called begin-end pair
74   assert(_pair);
75 }
76
77 void EventDurationManual::begin()
78 {
79   _pair = false;
80   auto &glob = EventCollectorGlobal::get();
81   glob.collector().onEvent(EventCollector::Event{EventCollector::Edge::BEGIN, "0", _tag});
82 }
83
84 void EventDurationManual::end()
85 {
86   assert(!_pair);
87   _pair = true;
88   auto &glob = EventCollectorGlobal::get();
89   glob.collector().onEvent(EventCollector::Event{EventCollector::Edge::END, "0", _tag});
90 }
91
92 } // namespace util
93 } // namespace onert