1 /* Copyright 2022 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/core/profiler/lib/profiler_controller.h" 16 17 #include <memory> 18 #include <utility> 19 20 #include "tensorflow/core/platform/errors.h" 21 #include "tensorflow/core/platform/logging.h" 22 #include "tensorflow/core/platform/status.h" 23 #include "tensorflow/core/profiler/lib/profiler_interface.h" 24 #include "tensorflow/core/profiler/protobuf/xplane.pb.h" 25 26 namespace tensorflow { 27 namespace profiler { 28 ProfilerController(std::unique_ptr<ProfilerInterface> profiler)29ProfilerController::ProfilerController( 30 std::unique_ptr<ProfilerInterface> profiler) 31 : profiler_(std::move(profiler)) {} 32 ~ProfilerController()33ProfilerController::~ProfilerController() { 34 // Ensure a successfully started profiler is stopped. 35 if (state_ == ProfilerState::kStart && status_.ok()) { 36 profiler_->Stop().IgnoreError(); 37 } 38 } 39 Start()40Status ProfilerController::Start() { 41 Status status; 42 if (state_ == ProfilerState::kInit) { 43 state_ = ProfilerState::kStart; 44 if (status_.ok()) { 45 status = status_ = profiler_->Start(); 46 } else { 47 status = errors::Aborted("Previous call returned an error."); 48 } 49 } else { 50 status = errors::Aborted("Start called in the wrong order"); 51 } 52 if (!status.ok()) LOG(ERROR) << status; 53 return status; 54 } 55 Stop()56Status ProfilerController::Stop() { 57 Status status; 58 if (state_ == ProfilerState::kStart) { 59 state_ = ProfilerState::kStop; 60 if (status_.ok()) { 61 status = status_ = profiler_->Stop(); 62 } else { 63 status = errors::Aborted("Previous call returned an error."); 64 } 65 } else { 66 status = errors::Aborted("Stop called in the wrong order"); 67 } 68 if (!status.ok()) LOG(ERROR) << status; 69 return status; 70 } 71 CollectData(XSpace * space)72Status ProfilerController::CollectData(XSpace* space) { 73 Status status; 74 if (state_ == ProfilerState::kStop) { 75 state_ = ProfilerState::kCollectData; 76 if (status_.ok()) { 77 status = status_ = profiler_->CollectData(space); 78 } else { 79 status = errors::Aborted("Previous call returned an error."); 80 } 81 } else { 82 status = errors::Aborted("CollectData called in the wrong order."); 83 } 84 if (!status.ok()) LOG(ERROR) << status; 85 return status; 86 } 87 88 } // namespace profiler 89 } // namespace tensorflow 90