text: // Copyright 2020 The TensorFlow Runtime Authors
  //
  // Licensed under the Apache License, Version 2.0 (the "License");
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  //
  //      http://www.apache.org/licenses/LICENSE-2.0
  //
  // Unless required by applicable law or agreed to in writing, software
  // distributed under the License is distributed on an "AS IS" BASIS,
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  // See the License for the specific language governing permissions and
  // limitations under the License.
  
  //===- tracing.cc - Tracing API -------------------------------------------===//
  //
  // This file implements the tracing library.
  //
  //===----------------------------------------------------------------------===//
  
  // This ifdef guard allows the user to compile the tracing support out.
  #ifndef NO_TFRT_TRACING
  #include "tfrt/tracing/tracing.h"
  
  namespace tfrt {
  namespace internal {
  namespace tracing {
  
  SteadyTimePoint CurrentSteadyClockTime() {
    return std::chrono::steady_clock::now();
  }
  
  TracingScope::TracingScope(tfrt::string_view title)
      : tracing_activity_({std::string(title), CurrentSteadyClockTime(), {}}) {}
  
  TracingScope::~TracingScope() {
    // Record the activity if it is not moved already.
    if (tracing_activity_.start_time != SteadyTimePoint()) {
      tracing_activity_.end_time = CurrentSteadyClockTime();
      TracingApi::RecordActivity(tracing_activity_);
    }
  }
  
  TracingScope::TracingScope(TracingScope&& t) noexcept
      : tracing_activity_(std::move(t.tracing_activity_)) {
    t.tracing_activity_.start_time =
        SteadyTimePoint();  // Marks the tracing_activity as moved.
  }
  
  void TracingApi::TurnTracingOn() {
    is_tracing_on_.store(record_activity_function_ != nullptr);
  }
  
  void TracingApi::TurnTracingOff() { is_tracing_on_.store(false); }
  
  void TracingApi::RegisterTracingSink(
      const std::string& sink_name,
      TracingSinkFunction record_activity_function) {
    record_activity_function_ = record_activity_function;
  }
  
  std::atomic<bool> TracingApi::is_tracing_on_{false};
  
  TracingSinkFunction* TracingApi::record_activity_function_{nullptr};
  
  }  // namespace tracing
  }  // namespace internal
  }  // namespace tfrt
  
  #endif  // NO_TFRT_TRACING
  