TopGit
Đánh giá repo GitHub

{fmt}: Thư viện format C++ nhanh

fmtlib/fmt
{TopGit review image for fmtlib/fmt
Review by Topgit.dev for fmtlib/fmt, with GitHub repository stats and README context.
Nhận định nhanh

{fmt} giữ đúng lời hứa về hiệu năng: benchmark cho thấy nhanh hơn printf 50%, và nhanh hơn std::ostringstream tới 30 lần cho floating-point, mà binary size không thay đổi. Chỉ riêng tính năng bắt lỗi format string lúc compile đã đáng để adopt — loại bỏ một class bug mà printf âm thầm nuốt chửng. Muốn format output trong C++? Chọn {fmt}, đừng tự viết hay chịu đựng iostreams.

Sao
★ 25.9k
Fork
⑂ 3.1k
Người đóng góp
👥 626
Ngôn ngữ
C++
Giấy phép
MIT
Chủ đề
Backend
Cập nhật
Nov 2026
Trang chủ
GitHub

{fmt} là gì?

{fmt} là thư viện format C++ làm lại những gì printf và iostreams làm, nhưng type-safe, nhanh hơn, và cú pháp sạch hơn. Format string dùng positional arguments kiểu Python's `str.format()`, format specifiers mirror Python's mini-language, và thư viện cover từ string interpolation cơ bản tới datetime formatting, range printing, và colored terminal output. Có thể dùng header-only hoặc build target chỉ 2 file + impl, không phụ thuộc bên ngoài.

Vấn đề với printf và iostreams

printf của C thì nhanh nhưng hoàn toàn không type-safe — truyền sai kiểu argument là undefined behavior, không compile error. iostreams của C++ thì type-safe nhưng cực kỳ chậm, verbose, và khó compose. Cả hai đều không feedback lỗi format string lúc compile. {fmt} giải quyết cả hai: cú pháp kiểu Python, được verify lúc compile, hiệu năng đánh bại printf, API sạch sẽ đến mức bạn sẽ không còn ngại việc format output trong C++.

Tính năng nổi bật

  • ✓Cú pháp kiểu Python với positional arguments cho localization
  • ✓Implement C++20 std::format và C++23 std::print — tuân thủ chuẩn mới nhất
  • ✓Kiểm tra format string lúc compile — lỗi được compiler bắt, không phải runtime
  • ✓Dragonbox algorithm cho IEEE 754 floats: đúng rounding, biểu diễn ngắn nhất, guaranteed round-trip
  • ✓Thay thế printf an toàn với POSIX positional arguments extension
  • ✓Header-only qua FMT_HEADER_ONLY macro; build tối thiểu chỉ 3 source file
  • ✓Type-safe toàn bộ — không format string vulnerabilities, không buffer overflows
  • ✓Cross-platform với output nhất quán trên mọi compiler và OS
Số sao GitHub của repo này thay đổi thế nào theo thời gian. Nguồn: star-history.com.Xem lịch sử sao ↗

Ví dụ thực tế

cpp #include <fmt/base.h> #include <fmt/chrono.h> #include <fmt/ranges.h> int main() { // Basic formatting mirrors Python's str.format() auto s = fmt::format("The answer is {}.", 42); // Positional args for localization auto localized = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); // Compile-time error: 'd' is invalid for strings // fmt::format("{:d}", "oops"); // won't compile // Datetime formatting auto now = std::chrono::system_clock::now(); fmt::print("Time: {%H:%M}\n", now); // Containers std::vector<int> v = {1, 2, 3}; fmt::print("{}\n", v); // prints [1, 2, 3] }

Cài đặt {fmt}

Clone repo vào thư mục third_party, rồi trỏ CMake find_package hoặc include_directories vào đó. Người dùng vcpkg: `vcpkg install fmt`. Người dùng Conan: `conan install fmt`. Minimum config gồm base.h, format.h, và format-inl.h — không cần build nếu dùng header-only mode bằng cách define FMT_HEADER_ONLY trước khi include bất kỳ fmt header nào.

So sánh với lựa chọn khác

Boost.Format — header-only nhưng benchmark của họ cho thấy compile chậm hơn 10x và binary lớn hơn 6-10x so với {fmt}Folly's format — alternative của Facebook, nhưng chậm hơn {fmt} 3x trong benchmark chính thức và gắn bạn với hệ sinh thái FollyStandard iostreams (std::ostream) — type-safe nhưng chậm hơn {fmt} 4x, API verboseprintf/fprintf — type-unsafe; undefined behavior khi argument mismatchspdlog — {fmt} dùng bên trong spdlog, nên spdlog là consumer downstream, không phải alternative trực tiếp cho việc format

Ai nên dùng {fmt}?

C++ developers viết code produce human-readable output và không hài lòng với printf's type unsafety hoặc iostreams' verbosity và performance. Game engine authors, database engineers, high-frequency trading systems, CLI tool maintainers, và ai thấy iostreams hoặc sprintf là bottleneck trong profile sẽ thấy gain ngay lập tức. Teams xây internationalized applications được lợi nhiều nhất từ positional argument support.

Câu hỏi thường gặp

{fmt} có tương thích với C++20 std::format không?

Có — {fmt} implement đặc tả C++20 std::format. Code targeting C++20 hoặc mới hơn có thể dùng std::format mà vẫn được performance của {fmt} thay vì standard library implementation thường chậm hơn. Thư viện cũng implement C++23 std::print.

{fmt} so với printf hoặc std::ostream về hiệu năng thì sao?

Benchmark của {fmt} cho thấy fmt::print nhanh hơn printf khoảng 50% và nhanh hơn std::ostream 3x trong điều kiện test của họ. Riêng floating-point formatting, {fmt} nhanh hơn std::ostringstream 20-30 lần. Binary size thì bằng printf.

{fmt} dùng license gì?

{fmt} phân phối dưới MIT license, rất permissive. Dùng trong commercial projects, sửa tự do, và redistribute với yêu cầu attribution tối thiểu.

{fmt} có hỗ trợ Unicode không?

Có — {fmt} hỗ trợ Unicode portable trên mọi platform. Xử lý UTF-8 strings natively, và module terminal output (fmt/color.h) hỗ trợ Unicode color codes và styled text cho terminals có hỗ trợ Unicode.

{fmt} có detect format string errors lúc compile không?

Có — ở C++20 mode, format specifiers không hợp lệ gây compile-time errors thay vì runtime crashes. Ví dụ, thử format string với specifier 'd' (integer) sẽ fail ngay lúc compile, bắt mistake trước khi code chạy.

{fmt} có external dependencies không?

Không — {fmt} không phụ thuộc bên ngoài. Minimum config chỉ ba file (base.h, format.h, format-inl.h), và header-only mode chỉ cần những headers đó. Drop vào project nào cũng được mà không cần pull thêm library.

Điểm mạnh

  • ✓Hiệu năng cao đi kèm safety: benchmark cho thấy nhanh hơn printf và C++ iostreams đáng kể, với compile-time format string validation và automatic memory management ngăn buffer overflows.
  • ✓Tích hợp C++ hiện đại: implement C++20 std::format và C++23 std::print, align với chuẩn C++ mới nhất, cú pháp format string giống Python cho familiarity.
  • ✓Overhead thấp, cross-platform: minimum config chỉ ba source files, không external dependencies, output nhất quán trên nhiều platform, hỗ trợ cả compilers cũ.
  • ✓Feature set rộng: floating-point formatting đặc biệt với correct rounding qua Dragonbox algorithm, Unicode portable support, và khả năng define custom formatters cho user-defined types.
  • ✓Được nhiều dự án lớn dùng: Apple's FoundationDB, MongoDB, PyTorch, Windows Terminal — thể hiện maturity và reliability trong production.

Hạn chế cần lưu ý

  • △Compile time tăng so với plain printf — {fmt} thêm khoảng 3 giây vào benchmark build so với printf's 1.6 giây, dù overhead này shared across translation units và không grow proportionally với usage
  • △C++20 compile-time format checking cần compiler có đầy đủ std::format support; toolchains cũ hơn chỉ validate runtime
  • △Thư viện có opinion về format syntax — dù match Python và C++ standard, developers quen với printf-style format strings có thể thấy mental shift không nhỏ
  • △Error messages cho compile-time format validation, dù tốt hơn runtime crashes, vẫn có thể cryptic với complex format strings trên một số compilers
  • △Như mọi third-party library, có dependency để manage — dù nhẹ và header-only, vẫn cần maintain trong các đợt upgrade toolchain

Trường hợp sử dụng phù hợp

  • •Thay printf/fprintf trong những code path nhạy cảm về hiệu năng
  • •Logging frameworks cần structured output throughput cao
  • •Ứng dụng numeric cần floating-point string conversion nhanh và chính xác
  • •Ứng dụng i18n dùng positional arguments để sắp xếp lại thứ tự
  • •Terminal apps muốn output có màu hoặc styled qua fmt/color.h
  • •Database và networking cần text serialization nhanh, đáng tin cậy

Repo liên quan

Nguồn & ghi công

Source: https://github.com/fmtlib/fmt

Dữ liệu GitHub · đồng bộ lần cuối 4 thg 9, 2026Đánh giá bởi Henry
← Về TopGit

fmt có đáng để bạn bỏ thời gian?

ChatGPT, Claude và Perplexity đều đọc được trang này. Hỏi thử xem họ nghĩ gì về fmt.

GitHub