1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #include "tensorflow/lite/profiling/memory_usage_monitor.h"
16
17 #include <memory>
18 #include <utility>
19
20 #include "absl/synchronization/notification.h"
21 #include "tensorflow/lite/minimal_logging.h"
22 #include "tensorflow/lite/profiling/memory_info.h"
23
24 namespace tflite {
25 namespace profiling {
26 namespace memory {
27
28 constexpr float MemoryUsageMonitor::kInvalidMemUsageMB;
29
MemoryUsageMonitor(int sampling_interval_ms,std::unique_ptr<Sampler> sampler)30 MemoryUsageMonitor::MemoryUsageMonitor(int sampling_interval_ms,
31 std::unique_ptr<Sampler> sampler)
32 : sampler_(std::move(sampler)),
33 is_supported_(false),
34 sampling_interval_(absl::Milliseconds(sampling_interval_ms)) {
35 is_supported_ = (sampler_ != nullptr && sampler_->IsSupported());
36 if (!is_supported_) {
37 TFLITE_LOG(TFLITE_LOG_INFO,
38 "Getting memory usage isn't supported on this platform!\n");
39 return;
40 }
41 }
42
Start()43 void MemoryUsageMonitor::Start() {
44 if (!is_supported_) return;
45 if (check_memory_thd_ != nullptr) {
46 TFLITE_LOG(TFLITE_LOG_INFO, "Memory monitoring has already started!\n");
47 return;
48 }
49
50 stop_signal_ = std::make_unique<absl::Notification>();
51 check_memory_thd_ = std::make_unique<std::thread>(([this]() {
52 // Note we retrieve the memory usage at the very beginning of the thread.
53 while (true) {
54 const auto mem_info = sampler_->GetMemoryUsage();
55 if (mem_info.max_rss_kb > peak_max_rss_kb_) {
56 peak_max_rss_kb_ = mem_info.max_rss_kb;
57 }
58 if (stop_signal_->HasBeenNotified()) break;
59 sampler_->SleepFor(sampling_interval_);
60 }
61 }));
62 }
63
Stop()64 void MemoryUsageMonitor::Stop() {
65 if (!is_supported_) return;
66 if (check_memory_thd_ == nullptr) {
67 TFLITE_LOG(TFLITE_LOG_INFO,
68 "Memory monitoring hasn't started yet or has stopped!\n");
69 return;
70 }
71 StopInternal();
72 }
73
StopInternal()74 void MemoryUsageMonitor::StopInternal() {
75 if (check_memory_thd_ == nullptr) return;
76 stop_signal_->Notify();
77 if (check_memory_thd_ != nullptr) {
78 check_memory_thd_->join();
79 }
80 stop_signal_.reset(nullptr);
81 check_memory_thd_.reset(nullptr);
82 }
83
84 } // namespace memory
85 } // namespace profiling
86 } // namespace tflite
87