fmtlib / fmt

fmtlib / fmt

{fmt} is an open-source formatting library providing a fast and safe alternative to C stdio and C++ iostreams. {fmt} 是一个开源的格式化库,为 C stdio 和 C++ iostreams 提供了一种快速且安全的替代方案。

Features

特性

  • Simple format API with positional arguments for localization 简洁的格式化 API,支持用于本地化的位置参数。
  • Implementation of C++20 std::format and C++23 std::print 实现了 C++20 的 std::format 和 C++23 的 std::print
  • Format string syntax similar to Python’s format 格式化字符串语法类似于 Python 的 format
  • Fast IEEE 754 floating-point formatter with correct rounding, shortness and round-trip guarantees using the Dragonbox algorithm 使用 Dragonbox 算法,提供快速的 IEEE 754 浮点数格式化,保证正确的舍入、最短长度和往返转换。
  • Portable Unicode support 可移植的 Unicode 支持。
  • Safe printf implementation including the POSIX extension for positional arguments 安全的 printf 实现,包括对位置参数的 POSIX 扩展。
  • Extensibility: support for user-defined types 可扩展性:支持用户自定义类型。
  • High performance: faster than common standard library implementations of (s)printf, iostreams, to_string and to_chars 高性能:比常见的标准库实现(如 (s)printf、iostreams、to_string 和 to_chars)更快。
  • Small code size: both in terms of source code and compiled code 代码体积小:无论是源代码还是编译后的代码。
  • Reliability: the library has an extensive set of tests and is continuously fuzzed 可靠性:该库拥有广泛的测试集,并持续进行模糊测试。
  • Safety: the library is fully type-safe, errors in format strings can be reported at compile time, automatic memory management prevents buffer overflow errors 安全性:该库完全类型安全,格式字符串中的错误可在编译时报告,自动内存管理可防止缓冲区溢出错误。
  • Ease of use: small self-contained code base, no external dependencies, permissive MIT license 易用性:代码库小巧且自包含,无外部依赖,采用宽松的 MIT 许可证。

Benchmarks: Speed tests

基准测试:速度测试

{fmt} is the fastest of the benchmarked methods, ~50% faster than printf. {fmt} 是所有基准测试方法中最快的,比 printf 快约 50%。

{fmt} is up to 20-30x faster than std::ostringstream and sprintf on IEEE754 float and double formatting (dtoa-benchmark) and faster than double-conversion and ryu. 在 IEEE754 浮点数和双精度浮点数格式化方面,{fmt} 比 std::ostringstreamsprintf 快 20-30 倍(基于 dtoa-benchmark),并且比 double-conversionryu 更快。


Compile time and code bloat

编译时间和代码膨胀

{fmt} is fast to compile and is comparable to printf in terms of per-call binary size. {fmt} 编译速度快,且在单次调用的二进制体积方面与 printf 相当。


Migrating code

代码迁移

clang-tidy v18 provides the modernize-use-std-print check that is capable of converting occurrences of printf and fprintf to fmt::print if configured to do so. (By default it converts to std::print.) clang-tidy v18 提供了 modernize-use-std-print 检查功能,如果进行相应配置,它可以将代码中的 printffprintf 转换为 fmt::print。(默认情况下,它会转换为 std::print。)


Notable projects using this library

使用该库的知名项目

  • 0 A.D.: a free, open-source, cross-platform real-time strategy game 0 A.D.:一款免费、开源、跨平台的即时战略游戏。
  • AMPL AMPL