1/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/core/common_runtime/cost_measurement_registry.h"
17
18#include <string>
19#include <utility>
20
21#include "absl/container/flat_hash_map.h"
22#include "absl/strings/string_view.h"
23#include "tensorflow/core/common_runtime/cost_measurement.h"
24#include "tensorflow/core/platform/logging.h"
25
26namespace tensorflow {
27namespace {
28
29using RegistrationMap =
30 absl::flat_hash_map<std::string, CostMeasurementRegistry::Creator>;
31
32RegistrationMap* GetRegistrationMap() {
33 static RegistrationMap* registered_cost_measurements = new RegistrationMap;
34 return registered_cost_measurements;
35}
36
37} // namespace
38
39std::unique_ptr<CostMeasurement> CostMeasurementRegistry::CreateByNameOrNull(
40 const std::string& name, const CostMeasurement::Context& context) {
41 const auto it = GetRegistrationMap()->find(name);
42 if (it == GetRegistrationMap()->end()) {
43 LOG_FIRST_N(ERROR, 1) << "Cost type " << name << " is unregistered.";
44 return nullptr;
45 }
46 return it->second(context);
47}
48
49void CostMeasurementRegistry::RegisterCostMeasurement(absl::string_view name,
50 Creator creator) {
51 const auto it = GetRegistrationMap()->find(name);
52 CHECK(it == GetRegistrationMap()->end()) // Crash OK
53 << "CostMeasurement " << name << " is registered twice.";
54 GetRegistrationMap()->emplace(name, std::move(creator));
55}
56
57} // namespace tensorflow
58