1 /* Copyright 2019 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/profiler/convert/op_metrics_to_record.h"
17 
18 #include <iterator>
19 #include <tuple>
20 #include <vector>
21 
22 #include "absl/algorithm/container.h"
23 #include "tensorflow/core/profiler/protobuf/op_metrics.pb.h"
24 
25 namespace tensorflow {
26 namespace profiler {
27 
SortedOpMetricsDb(const OpMetricsDb & metrics_db,int max_records)28 std::vector<const OpMetrics*> SortedOpMetricsDb(const OpMetricsDb& metrics_db,
29                                                 int max_records) {
30   std::vector<const OpMetrics*> result;
31   result.reserve(metrics_db.metrics_db_size());
32   for (const OpMetrics& metrics : metrics_db.metrics_db()) {
33     result.push_back(&metrics);
34   }
35 
36   auto comp = [](const OpMetrics* a, const OpMetrics* b) {
37     return std::make_tuple(a->self_time_ps(), b->name()) >
38            std::make_tuple(b->self_time_ps(), a->name());
39   };
40   int result_size = result.size();
41   if (max_records != -1 && result_size > max_records) {
42     absl::c_partial_sort(result, result.begin() + max_records, comp);
43     result.resize(max_records);
44   } else {
45     absl::c_sort(result, comp);
46   }
47   return result;
48 }
49 
50 }  // namespace profiler
51 }  // namespace tensorflow
52