647c51d54459a860d0064226d614ca17c15a826a
[platform/core/ml/nnfw.git] / runtime / contrib / heap_trace / src / trace.h
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 #ifndef TRACE_H_
18 #define TRACE_H_
19
20 #include <CL/cl.h>
21
22 #include <unordered_map>
23 #include <fstream>
24 #include <mutex>
25
26 class Trace
27 {
28   struct MemoryTraits
29   {
30     size_t ref_counter;
31     size_t size;
32
33     MemoryTraits(size_t init_counter_value, size_t size_of_allocated_memory)
34         : ref_counter(init_counter_value), size(size_of_allocated_memory)
35     {
36     }
37   };
38
39 public:
40   class Guard
41   {
42     friend class Trace;
43
44   public:
45     bool isActive() { return _is_trace_not_available || _is_recursion_detected; }
46
47   private:
48     void markTraceAsReady() { _is_trace_not_available = false; }
49     void markTraceAsNotReady() { _is_trace_not_available = true; }
50     void signalizeAboutPossibleRecursion() { _is_recursion_detected = true; }
51     void signalizeThatDangerOfRecursionHasPassed() { _is_recursion_detected = false; }
52
53   private:
54     static bool _is_trace_not_available;
55     static thread_local bool _is_recursion_detected;
56   };
57
58 public:
59   Trace();
60   Trace(const Trace &) = delete;
61   const Trace &operator=(const Trace &) = delete;
62
63   void logAllocationEvent(void *memory_ptr, size_t size_of_allocated_space_in_bytes);
64   void logAllocationEvent(cl_mem memory_ptr, size_t size_of_allocated_space_in_bytes);
65   void logDeallocationEvent(void *memory_ptr);
66   void logDeallocationEvent(cl_mem memory_ptr);
67
68   ~Trace();
69
70 private:
71   const char *getLogFileNameFromEnvVariable(const char *env_variable_name);
72
73 private:
74   std::mutex _lock;
75   std::ofstream _out;
76   size_t _total_allocated_bytes_on_cpu = 0;
77   size_t _total_deallocated_bytes_on_cpu = 0;
78   size_t _peak_heap_usage_on_cpu = 0;
79   size_t _total_allocated_bytes_on_gpu = 0;
80   size_t _total_deallocated_bytes_on_gpu = 0;
81   size_t _peak_heap_usage_on_gpu = 0;
82   std::unordered_map<void *, size_t> _memory_in_use_on_cpu;
83   std::unordered_map<cl_mem, MemoryTraits> _memory_in_use_on_gpu;
84 };
85
86 #endif // !TRACE_H