4 .. image:: https://travis-ci.org/fmtlib/fmt.png?branch=master
5 :target: https://travis-ci.org/fmtlib/fmt
7 .. image:: https://ci.appveyor.com/api/projects/status/ehjkiefde6gucy1v
8 :target: https://ci.appveyor.com/project/vitaut/fmt
10 .. image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/libfmt.svg
11 :alt: fmt is continuously fuzzed att oss-fuzz
12 :target: https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dlibfmt&can=1
14 .. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg
15 :alt: Ask questions at StackOverflow with the tag fmt
16 :target: https://stackoverflow.com/questions/tagged/fmt
18 **{fmt}** is an open-source formatting library for C++.
19 It can be used as a safe and fast alternative to (s)printf and iostreams.
21 `Documentation <https://fmt.dev/latest/>`__
23 Q&A: ask questions on `StackOverflow with the tag fmt <https://stackoverflow.com/questions/tagged/fmt>`_.
28 * Replacement-based `format API <https://fmt.dev/dev/api.html>`_ with
29 positional arguments for localization.
30 * `Format string syntax <https://fmt.dev/dev/syntax.html>`_ similar to the one
31 of `str.format <https://docs.python.org/3/library/stdtypes.html#str.format>`_
33 * Safe `printf implementation
34 <https://fmt.dev/latest/api.html#printf-formatting>`_ including
35 the POSIX extension for positional arguments.
36 * Implementation of `C++20 std::format <https://en.cppreference.com/w/cpp/utility/format>`__.
37 * Support for user-defined types.
38 * High performance: faster than common standard library implementations of
39 `printf <https://en.cppreference.com/w/cpp/io/c/fprintf>`_ and
40 iostreams. See `Speed tests`_ and `Fast integer to string conversion in C++
41 <http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html>`_.
42 * Small code size both in terms of source code (the minimum configuration
43 consists of just three header files, ``core.h``, ``format.h`` and
44 ``format-inl.h``) and compiled code. See `Compile time and code bloat`_.
45 * Reliability: the library has an extensive set of `unit tests
46 <https://github.com/fmtlib/fmt/tree/master/test>`_ and is continuously fuzzed.
47 * Safety: the library is fully type safe, errors in format strings can be
48 reported at compile time, automatic memory management prevents buffer overflow
50 * Ease of use: small self-contained code base, no external dependencies,
51 permissive MIT `license
52 <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_
53 * `Portability <https://fmt.dev/latest/index.html#portability>`_ with
54 consistent output across platforms and support for older compilers.
55 * Clean warning-free codebase even on high warning levels
56 (``-Wall -Wextra -pedantic``).
57 * Support for wide strings.
58 * Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro.
60 See the `documentation <https://fmt.dev/latest/>`_ for more details.
65 Print ``Hello, world!`` to ``stdout``:
69 fmt::print("Hello, {}!", "world"); // Python-like format string syntax
70 fmt::printf("Hello, %s!", "world"); // printf format string syntax
72 Format a string and use positional arguments:
76 std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
77 // s == "I'd rather be happy than right."
79 Check a format string at compile time:
84 #include <fmt/format.h>
85 std::string s = format(FMT_STRING("{2}"), 42);
89 $ c++ -Iinclude -std=c++14 test.cc
91 test.cc:4:17: note: in instantiation of function template specialization 'fmt::v5::format<S, int>' requested here
92 std::string s = format(FMT_STRING("{2}"), 42);
94 include/fmt/core.h:778:19: note: non-constexpr function 'on_error' cannot be used in a constant expression
95 ErrorHandler::on_error(message);
97 include/fmt/format.h:2226:16: note: in call to '&checker.context_->on_error(&"argument index out of range"[0])'
98 context_.on_error("argument index out of range");
101 Use {fmt} as a safe portable replacement for ``itoa``
102 (`godbolt <https://godbolt.org/g/NXmpU4>`_):
106 fmt::memory_buffer buf;
107 format_to(buf, "{}", 42); // replaces itoa(42, buffer, 10)
108 format_to(buf, "{:x}", 42); // replaces itoa(42, buffer, 16)
109 // access the string with to_string(buf) or buf.data()
111 Format objects of user-defined types via a simple `extension API
112 <https://fmt.dev/latest/api.html#formatting-user-defined-types>`_:
116 #include "fmt/format.h"
119 int year, month, day;
123 struct fmt::formatter<date> {
124 constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
126 template <typename FormatContext>
127 auto format(const date& d, FormatContext& ctx) {
128 return format_to(ctx.out(), "{}-{}-{}", d.year, d.month, d.day);
132 std::string s = fmt::format("The date is {}", date{2012, 12, 9});
133 // s == "The date is 2012-12-9"
135 Create your own functions similar to `format
136 <https://fmt.dev/latest/api.html#format>`_ and
137 `print <https://fmt.dev/latest/api.html#print>`_
138 which take arbitrary arguments (`godbolt <https://godbolt.org/g/MHjHVf>`_):
142 // Prints formatted error message.
143 void vreport_error(const char* format, fmt::format_args args) {
144 fmt::print("Error: ");
145 fmt::vprint(format, args);
147 template <typename... Args>
148 void report_error(const char* format, const Args & ... args) {
149 vreport_error(format, fmt::make_format_args(args...));
152 report_error("file not found: {}", path);
154 Note that ``vreport_error`` is not parameterized on argument types which can
155 improve compile times and reduce code size compared to a fully parameterized
164 ================= ============= ===========
165 Library Method Run Time, s
166 ================= ============= ===========
168 libc++ std::ostream 3.05
169 {fmt} 6.1.1 fmt::print 0.75
170 Boost Format 1.67 boost::format 7.24
171 Folly Format folly::format 2.23
172 ================= ============= ===========
174 {fmt} is the fastest of the benchmarked methods, ~35% faster than ``printf``.
176 The above results were generated by building ``tinyformat_test.cpp`` on macOS
177 10.14.6 with ``clang++ -O3 -DSPEED_TEST -DHAVE_FORMAT``, and taking the best of
178 three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"``
179 or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for
180 further details refer to the `source
181 <https://github.com/fmtlib/format-benchmark/blob/master/tinyformat_test.cpp>`_.
183 {fmt} is 10x faster than ``std::ostringstream`` and ``sprintf`` on floating-point
184 formatting (`dtoa-benchmark <https://github.com/fmtlib/dtoa-benchmark>`_)
185 and as fast as `double-conversion <https://github.com/google/double-conversion>`_:
187 .. image:: https://user-images.githubusercontent.com/576385/69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png
188 :target: https://fmt.dev/unknown_mac64_clang10.0.html
190 Compile time and code bloat
191 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
193 The script `bloat-test.py
194 <https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py>`_
195 from `format-benchmark <https://github.com/fmtlib/format-benchmark>`_
196 tests compile time and code bloat for nontrivial projects.
197 It generates 100 translation units and uses ``printf()`` or its alternative
198 five times in each to simulate a medium sized project. The resulting
199 executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42),
200 macOS Sierra, best of three) is shown in the following tables.
202 **Optimized build (-O3)**
204 ============= =============== ==================== ==================
205 Method Compile Time, s Executable size, KiB Stripped size, KiB
206 ============= =============== ==================== ==================
208 printf+string 16.4 29 26
211 Boost Format 91.9 226 203
212 Folly Format 115.7 101 88
213 ============= =============== ==================== ==================
215 As you can see, {fmt} has 60% less overhead in terms of resulting binary code
216 size compared to iostreams and comes pretty close to ``printf``. Boost Format
217 and Folly Format have the largest overheads.
219 ``printf+string`` is the same as ``printf`` but with extra ``<string>``
220 include to measure the overhead of the latter.
222 **Non-optimized build**
224 ============= =============== ==================== ==================
225 Method Compile Time, s Executable size, KiB Stripped size, KiB
226 ============= =============== ==================== ==================
228 printf+string 16.0 33 30
231 Boost Format 54.1 365 303
232 Folly Format 79.9 445 430
233 ============= =============== ==================== ==================
235 ``libc``, ``lib(std)c++`` and ``libfmt`` are all linked as shared libraries to
236 compare formatting function overhead only. Boost Format is a
237 header-only library so it doesn't provide any linkage options.
242 Please refer to `Building the library`__ for the instructions on how to build
243 the library and run the unit tests.
245 __ https://fmt.dev/latest/usage.html#building-the-library
247 Benchmarks reside in a separate repository,
248 `format-benchmarks <https://github.com/fmtlib/format-benchmark>`_,
249 so to run the benchmarks you first need to clone this repository and
250 generate Makefiles with CMake::
252 $ git clone --recursive https://github.com/fmtlib/format-benchmark.git
253 $ cd format-benchmark
256 Then you can run the speed test::
264 Projects using this library
265 ---------------------------
267 * `0 A.D. <https://play0ad.com/>`_: A free, open-source, cross-platform
268 real-time strategy game
270 * `AMPL/MP <https://github.com/ampl/mp>`_:
271 An open-source library for mathematical programming
273 * `AvioBook <https://www.aviobook.aero/en>`_: A comprehensive aircraft
276 * `Celestia <https://celestia.space/>`_: Real-time 3D visualization of space
278 * `Ceph <https://ceph.com/>`_: A scalable distributed storage system
280 * `ccache <https://ccache.dev/>`_: A compiler cache
282 * `CUAUV <http://cuauv.org/>`_: Cornell University's autonomous underwater
285 * `Drake <https://drake.mit.edu/>`_: A planning, control, and analysis toolbox
286 for nonlinear dynamical systems (MIT)
288 * `Envoy <https://lyft.github.io/envoy/>`_: C++ L7 proxy and communication bus
291 * `FiveM <https://fivem.net/>`_: a modification framework for GTA V
293 * `Folly <https://github.com/facebook/folly>`_: Facebook open-source library
295 * `HarpyWar/pvpgn <https://github.com/pvpgn/pvpgn-server>`_:
296 Player vs Player Gaming Network with tweaks
298 * `KBEngine <https://kbengine.org/>`_: An open-source MMOG server engine
300 * `Keypirinha <https://keypirinha.com/>`_: A semantic launcher for Windows
302 * `Kodi <https://kodi.tv/>`_ (formerly xbmc): Home theater software
304 * `Knuth <https://kth.cash/>`_: High-performance Bitcoin full-node
306 * `Microsoft Verona <https://github.com/microsoft/verona>`_: Research programming language for concurrent ownership
308 * `MongoDB <https://mongodb.com/>`_: Distributed document database
310 * `MongoDB Smasher <https://github.com/duckie/mongo_smasher>`_: A small tool to
311 generate randomized datasets
313 * `OpenSpace <https://openspaceproject.com/>`_: An open-source
314 astrovisualization framework
316 * `PenUltima Online (POL) <https://www.polserver.com/>`_:
317 An MMO server, compatible with most Ultima Online clients
319 * `PyTorch <https://github.com/pytorch/pytorch>`_: An open-source machine
322 * `quasardb <https://www.quasardb.net/>`_: A distributed, high-performance,
325 * `readpe <https://bitbucket.org/sys_dev/readpe>`_: Read Portable Executable
327 * `redis-cerberus <https://github.com/HunanTV/redis-cerberus>`_: A Redis cluster
330 * `redpanda <https://vectorized.io/redpanda>`_: A 10x faster Kafka® replacement
331 for mission critical systems written in C++
333 * `rpclib <http://rpclib.net/>`_: A modern C++ msgpack-RPC server and client
336 * `Salesforce Analytics Cloud
337 <https://www.salesforce.com/analytics-cloud/overview/>`_:
338 Business intelligence software
340 * `Scylla <https://www.scylladb.com/>`_: A Cassandra-compatible NoSQL data store
341 that can handle 1 million transactions per second on a single server
343 * `Seastar <http://www.seastar-project.org/>`_: An advanced, open-source C++
344 framework for high-performance server applications on modern hardware
346 * `spdlog <https://github.com/gabime/spdlog>`_: Super fast C++ logging library
348 * `Stellar <https://www.stellar.org/>`_: Financial platform
350 * `Touch Surgery <https://www.touchsurgery.com/>`_: Surgery simulator
352 * `TrinityCore <https://github.com/TrinityCore/TrinityCore>`_: Open-source
355 * `Windows Terminal <https://github.com/microsoft/terminal>`_: The new Windows
358 `More... <https://github.com/search?q=fmtlib&type=Code>`_
360 If you are aware of other projects using this library, please let me know
361 by `email <mailto:victor.zverovich@gmail.com>`_ or by submitting an
362 `issue <https://github.com/fmtlib/fmt/issues>`_.
367 So why yet another formatting library?
369 There are plenty of methods for doing this task, from standard ones like
370 the printf family of function and iostreams to Boost Format and FastFormat
371 libraries. The reason for creating a new library is that every existing
372 solution that I found either had serious issues or didn't provide
373 all the features I needed.
378 The good thing about ``printf`` is that it is pretty fast and readily available
379 being a part of the C standard library. The main drawback is that it
380 doesn't support user-defined types. ``printf`` also has safety issues although
381 they are somewhat mitigated with `__attribute__ ((format (printf, ...))
382 <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ in GCC.
383 There is a POSIX extension that adds positional arguments required for
384 `i18n <https://en.wikipedia.org/wiki/Internationalization_and_localization>`_
385 to ``printf`` but it is not a part of C99 and may not be available on some
391 The main issue with iostreams is best illustrated with an example:
395 std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n";
397 which is a lot of typing compared to printf:
401 printf("%.2f\n", 1.23456);
403 Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams
404 don't support positional arguments by design.
406 The good part is that iostreams support user-defined types and are safe although
407 error handling is awkward.
412 This is a very powerful library which supports both ``printf``-like format
413 strings and positional arguments. Its main drawback is performance. According to
414 various benchmarks it is much slower than other methods considered here. Boost
415 Format also has excessive build times and severe code bloat issues (see
421 This is an interesting library which is fast, safe and has positional
422 arguments. However it has significant limitations, citing its author:
424 Three features that have no hope of being accommodated within the
427 * Leading zeros (or any other non-space padding)
428 * Octal/hexadecimal encoding
429 * Runtime width/alignment specification
431 It is also quite big and has a heavy dependency, STLSoft, which might be
432 too restrictive for using it in some projects.
437 This is not really a formatting library but I decided to include it here for
438 completeness. As iostreams, it suffers from the problem of mixing verbatim text
439 with arguments. The library is pretty fast, but slower on integer formatting
440 than ``fmt::format_int`` on Karma's own benchmark,
441 see `Fast integer to string conversion in C++
442 <http://zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html>`_.
447 Q: how can I capture formatting arguments and format them later?
449 A: use ``std::tuple``:
453 template <typename... Args>
454 auto capture(const Args&... args) {
455 return std::make_tuple(args...);
458 auto print_message = [](const auto&... args) {
462 // Capture and store arguments:
463 auto args = capture("{} {}", 42, "foo");
465 std::apply(print_message, args);
470 {fmt} is distributed under the MIT `license
471 <https://github.com/fmtlib/fmt/blob/master/LICENSE.rst>`_.
473 The `Format String Syntax
474 <https://fmt.dev/latest/syntax.html>`_
475 section in the documentation is based on the one from Python `string module
476 documentation <https://docs.python.org/3/library/string.html#module-string>`_
477 adapted for the current library. For this reason the documentation is
478 distributed under the Python Software Foundation license available in
479 `doc/python-license.txt
480 <https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt>`_.
481 It only applies if you distribute the documentation of fmt.
486 The {fmt} library is maintained by Victor Zverovich (`vitaut
487 <https://github.com/vitaut>`_) and Jonathan Müller (`foonathan
488 <https://github.com/foonathan>`_) with contributions from many other people.
489 See `Contributors <https://github.com/fmtlib/fmt/graphs/contributors>`_ and
490 `Releases <https://github.com/fmtlib/fmt/releases>`_ for some of the names.
491 Let us know if your contribution is not listed or mentioned incorrectly and
494 The benchmark section of this readme file and the performance tests are taken
495 from the excellent `tinyformat <https://github.com/c42f/tinyformat>`_ library
496 written by Chris Foster. Boost Format library is acknowledged transitively
497 since it had some influence on tinyformat.
498 Some ideas used in the implementation are borrowed from `Loki
499 <http://loki-lib.sourceforge.net/>`_ SafeFormat and `Diagnostic API
500 <https://clang.llvm.org/doxygen/classclang_1_1Diagnostic.html>`_ in
501 `Clang <https://clang.llvm.org/>`_.
502 Format string syntax and the documentation are based on Python's `str.format
503 <https://docs.python.org/3/library/stdtypes.html#str.format>`_.
504 Thanks `Doug Turnbull <https://github.com/softwaredoug>`_ for his valuable
505 comments and contribution to the design of the type-safe API and
506 `Gregory Czajkowski <https://github.com/gcflymoto>`_ for implementing binary
507 formatting. Thanks `Ruslan Baratov <https://github.com/ruslo>`_ for comprehensive
508 `comparison of integer formatting algorithms <https://github.com/ruslo/int-dec-format-tests>`_
509 and useful comments regarding performance, `Boris Kaul <https://github.com/localvoid>`_ for
510 `C++ counting digits benchmark <https://github.com/localvoid/cxx-benchmark-count-digits>`_.
511 Thanks to `CarterLi <https://github.com/CarterLi>`_ for contributing various
512 improvements to the code.