1 /* Copyright 2020 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 #ifndef TENSORFLOW_CORE_PROFILER_LIB_ANNOTATED_TRACEME_H_ 16 #define TENSORFLOW_CORE_PROFILER_LIB_ANNOTATED_TRACEME_H_ 17 18 #include <utility> 19 20 #include "absl/strings/string_view.h" 21 #include "absl/types/optional.h" 22 #include "tensorflow/core/platform/logging.h" 23 #include "tensorflow/core/platform/macros.h" 24 #include "tensorflow/core/platform/types.h" 25 #include "tensorflow/core/profiler/lib/scoped_annotation.h" 26 #include "tensorflow/core/profiler/lib/traceme.h" 27 28 namespace tensorflow { 29 namespace profiler { 30 31 // Combination of TraceMe and ScopedAnnotation which share the same label. 32 // Optimization are done to ensure the label generation are done once. 33 class AnnotatedTraceMe { 34 public: 35 template <typename NameGeneratorT> 36 explicit AnnotatedTraceMe(NameGeneratorT name_generator, int level = 1) { 37 DCHECK_GE(level, 1); 38 bool annotation_enabled = ScopedAnnotation::IsEnabled(); 39 bool traceme_enabled = TraceMe::Active(level); 40 if (TF_PREDICT_FALSE(annotation_enabled || traceme_enabled)) { 41 string name = name_generator(); 42 if (annotation_enabled) { 43 scoped_annotation_.emplace(absl::string_view(name)); 44 } 45 if (TF_PREDICT_TRUE(traceme_enabled)) { 46 trace_me_.emplace([&name] { return std::move(name); }, level); 47 } 48 } 49 } 50 51 private: 52 absl::optional<TraceMe> trace_me_; 53 absl::optional<ScopedAnnotation> scoped_annotation_; 54 }; 55 56 } // namespace profiler 57 } // namespace tensorflow 58 59 #endif // TENSORFLOW_CORE_PROFILER_LIB_ANNOTATED_TRACEME_H_ 60