1 /* Copyright 2015 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_COMPILER_XLA_STREAM_EXECUTOR_LIB_HUMAN_READABLE_H_ 17 #define TENSORFLOW_COMPILER_XLA_STREAM_EXECUTOR_LIB_HUMAN_READABLE_H_ 18 19 #include <assert.h> 20 21 #include <limits> 22 23 #include "absl/strings/str_format.h" 24 #include "tensorflow/compiler/xla/stream_executor/platform/port.h" 25 26 namespace stream_executor { 27 namespace port { 28 29 class HumanReadableNumBytes { 30 public: ToString(int64_t num_bytes)31 static std::string ToString(int64_t num_bytes) { 32 if (num_bytes == std::numeric_limits<int64_t>::min()) { 33 // Special case for number with not representable nagation. 34 return "-8E"; 35 } 36 37 const char* neg_str = GetNegStr(&num_bytes); 38 39 // Special case for bytes. 40 if (num_bytes < 1024LL) { 41 // No fractions for bytes. 42 return absl::StrFormat("%s%dB", neg_str, num_bytes); 43 } 44 45 static const char units[] = "KMGTPE"; // int64_t only goes up to E. 46 const char* unit = units; 47 while (num_bytes >= (1024LL) * (1024LL)) { 48 num_bytes /= (1024LL); 49 ++unit; 50 assert(unit < units + sizeof(units)); 51 } 52 53 if (*unit == 'K') { 54 return absl::StrFormat("%s%.1f%c", neg_str, num_bytes / 1024.0, *unit); 55 } 56 return absl::StrFormat("%s%.2f%c", neg_str, num_bytes / 1024.0, *unit); 57 } 58 59 private: 60 template <typename T> GetNegStr(T * value)61 static const char* GetNegStr(T* value) { 62 if (*value < 0) { 63 *value = -(*value); 64 return "-"; 65 } else { 66 return ""; 67 } 68 } 69 }; 70 71 } // namespace port 72 } // namespace stream_executor 73 74 #endif // TENSORFLOW_COMPILER_XLA_STREAM_EXECUTOR_LIB_HUMAN_READABLE_H_ 75