Skip to content

Instantly share code, notes, and snippets.

@azat
Last active March 6, 2025 14:58
Show Gist options
  • Select an option

  • Save azat/eccb1ca634417bb7b1bfbfb8a755987f to your computer and use it in GitHub Desktop.

Select an option

Save azat/eccb1ca634417bb7b1bfbfb8a755987f to your computer and use it in GitHub Desktop.
// Written with ChatGPT
#include <iostream>
#include <chrono>
#include <format>
#include <print>
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/chrono.h>
#include <fmt/ranges.h>
constexpr int ITERATIONS = 1'000'000;
template <typename Func>
auto benchmark(Func&& func, const std::string& name) {
auto start = std::chrono::high_resolution_clock::now();
func();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end - start;
std::cout << name << ": " << duration.count() << " ms\n";
}
int main() {
std::string result;
benchmark([] {
for (int i = 0; i < ITERATIONS; ++i) {
std::format("Hello, {}! The answer is {}.", "world", 42);
}
}, "std::format");
benchmark([] {
for (int i = 0; i < ITERATIONS; ++i) {
fmt::format("Hello, {}! The answer is {}.", "world", 42);
}
}, "fmt::format");
benchmark([&result] {
for (int i = 0; i < ITERATIONS; ++i) {
result = std::format("Hello, {}! The answer is {}.", "world", 42);
}
}, "std::format (with assignment)");
benchmark([&result] {
for (int i = 0; i < ITERATIONS; ++i) {
result = fmt::format("Hello, {}! The answer is {}.", "world", 42);
}
}, "fmt::format (with assignment)");
/* benchmark([] { */
/* for (int i = 0; i < ITERATIONS; ++i) { */
/* std::print("Hello, {}! The answer is {}.\n", "world", 42); */
/* } */
/* }, "std::print"); */
/* benchmark([] { */
/* for (int i = 0; i < ITERATIONS; ++i) { */
/* fmt::print("Hello, {}! The answer is {}.\n", "world", 42); */
/* } */
/* }, "fmt::print"); */
return 0;
}
@azat

azat commented Mar 6, 2025

Copy link
Copy Markdown
Author
std::format: 76.9111 ms
fmt::format: 50.1275 ms
std::format (with assignment): 60.5027 ms
fmt::format (with assignment): 51.9799 ms

@azat

azat commented Mar 6, 2025

Copy link
Copy Markdown
Author

Results looks odd, why does with assigment works faster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment