1 /* Copyright 2018 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_PROFILER_SESSION_H_ 16 #define TENSORFLOW_CORE_PROFILER_LIB_PROFILER_SESSION_H_ 17 18 #include "tensorflow/core/common_runtime/eager/context.h" 19 #include "tensorflow/core/lib/core/status.h" 20 #include "tensorflow/core/platform/mutex.h" 21 #include "tensorflow/core/profiler/internal/profiler_interface.h" 22 23 namespace tensorflow { 24 25 struct ProfilerContext { 26 EagerContext* eager_context = nullptr; 27 }; 28 29 // A profiler which will start profiling when creating the object and will stop 30 // when either the object is destroyed or SerializedToString is called. It will 31 // profile all operations run under the given EagerContext. 32 // Multiple instances of it can be created, but at most one of them will profile 33 // for each EagerContext. Status() will return OK only for the instance that is 34 // profiling. 35 // Thread-safety: ProfilerSession is thread-safe. 36 class ProfilerSession { 37 public: 38 // Creates and ProfilerSession and starts profiling. 39 static std::unique_ptr<ProfilerSession> Create( 40 ProfilerContext* const context); 41 42 // Deletes an exsiting Profiler and enables starting a new one. 43 ~ProfilerSession(); 44 45 tensorflow::Status Status() LOCKS_EXCLUDED(mutex_); 46 47 tensorflow::Status SerializeToString(string* content) LOCKS_EXCLUDED(mutex_); 48 49 private: 50 // Constructs an instance of the class and starts profiling 51 explicit ProfilerSession(ProfilerContext* const context); 52 53 // Profiler is neither copyable or movable. 54 ProfilerSession(const ProfilerSession&) = delete; 55 ProfilerSession& operator=(const ProfilerSession&) = delete; 56 57 std::vector<std::unique_ptr<tensorflow::profiler::ProfilerInterface>> 58 profilers_ GUARDED_BY(mutex_); 59 60 // True if the session is active. 61 bool active_ GUARDED_BY(mutex_); 62 63 tensorflow::Status status_ GUARDED_BY(mutex_); 64 const uint64 start_time_micros_; 65 mutex mutex_; 66 }; 67 68 } // namespace tensorflow 69 #endif // TENSORFLOW_CORE_PROFILER_LIB_PROFILER_SESSION_H_ 70