1 /* Copyright 2020 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 #ifndef TENSORFLOW_CORE_PROFILER_UTILS_FORMAT_UTILS_H_
17 #define TENSORFLOW_CORE_PROFILER_UTILS_FORMAT_UTILS_H_
18 
19 #include <stdio.h>
20 
21 #include <string>
22 
23 #include "tensorflow/core/platform/logging.h"
24 
25 namespace tensorflow {
26 namespace profiler {
27 namespace internal {
28 
FormatDouble(const char * fmt,double d)29 inline std::string FormatDouble(const char* fmt, double d) {
30   constexpr int kBufferSize = 32;
31   char buffer[kBufferSize];
32   int result = snprintf(buffer, kBufferSize, fmt, d);
33   DCHECK(result > 0 && result < kBufferSize);
34   return std::string(buffer);
35 }
36 
37 }  // namespace internal
38 
39 // Formats d with one digit after the decimal point.
OneDigit(double d)40 inline std::string OneDigit(double d) {
41   return internal::FormatDouble("%.1f", d);
42 }
43 
44 // Formats d with maximum precision to allow parsing the result back to the same
45 // number.
MaxPrecision(double d)46 inline std::string MaxPrecision(double d) {
47   return internal::FormatDouble("%.17g", d);
48 }
49 
50 }  // namespace profiler
51 }  // namespace tensorflow
52 
53 #endif  // TENSORFLOW_CORE_PROFILER_UTILS_FORMAT_UTILS_H_
54