xref: /aosp_15_r20/external/tensorflow/tensorflow/core/common_runtime/cost_util.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2021 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 
16 #include "tensorflow/core/common_runtime/cost_util.h"
17 
18 #include <memory>
19 #include <string>
20 #include <utility>
21 #include <vector>
22 
23 #include "tensorflow/core/common_runtime/cost_measurement.h"
24 #include "tensorflow/core/common_runtime/cost_measurement_registry.h"
25 #include "tensorflow/core/common_runtime/request_cost_accessor_registry.h"
26 #include "tensorflow/core/platform/str_util.h"
27 
28 namespace tensorflow {
29 
30 namespace {
31 
32 // Gets the types of CostMeasurement from env.
GetCostMeasurementTypes()33 std::vector<std::string> GetCostMeasurementTypes() {
34   const char* types = std::getenv("TF_COST_MEASUREMENT_TYPE");
35   if (types == nullptr) return {};
36   return str_util::Split(types, " ,");
37 }
38 
39 // Gets the type of RequestCostAccessor from env.
GetRequestCostAccessorType()40 const char* GetRequestCostAccessorType() {
41   static const char* accessor = std::getenv("TF_REQUEST_COST_ACCESSOR_TYPE");
42   return accessor;
43 }
44 
45 }  // namespace
46 
CreateCostMeasurements(const CostMeasurement::Context & context)47 std::vector<std::unique_ptr<CostMeasurement>> CreateCostMeasurements(
48     const CostMeasurement::Context& context) {
49   static const std::vector<std::string>& types =
50       *new std::vector<std::string>(GetCostMeasurementTypes());
51 
52   std::vector<std::unique_ptr<CostMeasurement>> measurements;
53   for (const auto& type : types) {
54     std::unique_ptr<CostMeasurement> measurement =
55         CostMeasurementRegistry::CreateByNameOrNull(type, context);
56     if (measurement != nullptr) {
57       measurements.push_back(std::move(measurement));
58     }
59   }
60   return measurements;
61 }
62 
CreateRequestCostAccessor()63 std::unique_ptr<RequestCostAccessor> CreateRequestCostAccessor() {
64   const char* request_cost_accessor_type = GetRequestCostAccessorType();
65   return request_cost_accessor_type
66              ? RequestCostAccessorRegistry::CreateByNameOrNull(
67                    request_cost_accessor_type)
68              : nullptr;
69 }
70 
71 }  // namespace tensorflow
72