Closed
Description
Manual implementation is about 10 times faster than fmtlib.
MSVC x64
Manual: 2414
Fmt: 16481
#include <string>
#include <iostream>
#include <chrono>
#include <fmt/format.h>
constexpr char hexchar[] = "0123456789ABCDEF";
template <typename T>
std::string to_hex(T value)
{
constexpr size_t sz = sizeof(value) * 2;
std::string buffer(sz, L'\0');
for (int i = 0; i < 2 * sizeof(value); i++)
buffer[i] = hexchar[(value >> 4 * (sz - 1 - i)) & 0xf];
return buffer;
}
template <typename T>
std::string fmt_to_hex(T value)
{
return fmt::format(FMT_STRING("{0:X}"), value);
}
int main()
{
int sum = 0;
auto before = std::chrono::system_clock::now();
for (int i = 0; i < 100000000; i++)
{
auto a = to_hex(i);
sum += a.length();
}
auto manual = std::chrono::system_clock::now() - before;
before= std::chrono::system_clock::now();
for (int i = 0; i < 100000000; i++)
{
auto a = fmt_to_hex(i);
sum += a.length();
}
auto fmt= std::chrono::system_clock::now() -before;
std::cout << "Manual: " << duration_cast<std::chrono::milliseconds>(manual).count() << std::endl;
std::cout << "Fmt: " << duration_cast<std::chrono::milliseconds>(fmt).count() << std::endl;
return sum;
}
Metadata
Metadata
Assignees
Labels
No labels