1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
#include <string>
#include <sstream>
#include <charconv>
#include <type_traits>
#include <string_view>
#include <chrono>
#include <iostream>
template<typename T>
std::string toHex1(T val) {
std::stringstream ss;
ss << std::hex << val;
return ss.str();
}
template <typename T>
std::string toHex2(T w) {
static const char* const digits {"0123456789ABCDEF"};
std::string rc(sizeof(T) << 1, '0');
auto itr {rc.rbegin()};
for (; w; w >>= 4)
*itr++ = digits[w & 0x0f];
return itr == rc.rbegin() ? "0" : std::string(itr.base(), rc.end());
}
template <typename I>
std::string toHex3(I w) {
std::string rc(sizeof(I) << 1, '0');
return {rc.data(), std::to_chars(rc.data(), rc.data() + rc.size(), w, 16).ptr};
}
template <typename T>
typename std::enable_if_t< std::is_integral_v<T>, std::string_view> toHex4(T value) {
static char buffer[128];
const auto [ptr, ec] = std::to_chars(buffer, buffer + sizeof(buffer), value, 16);
return {buffer, std::size_t(ptr - buffer)};
}
template <typename T>
typename std::enable_if_t< std::is_integral_v<T>, std::string> toHex5(T value) {
return std::string(toHex4(value));
}
class Timer
{
public:
Timer(const char* name) : name_(name), start(std::chrono::high_resolution_clock::now()) {}
~Timer() {
const auto diff {std::chrono::high_resolution_clock::now() - start};
std::cout << name_ << " took " << std::chrono::duration<double, std::milli>(diff).count() << " ms\n";
}
private:
std::string name_;
decltype(std::chrono::high_resolution_clock::now()) start {};
};
int main()
{
constexpr size_t iters {5'000'000};
{
Timer t("stream");
for (size_t i = 0; i < iters; ++i)
toHex1(i);
}
{
Timer t("loop");
for (size_t i = 0; i < iters; ++i)
toHex2(i);
}
{
Timer t("to chars");
for (size_t i = 0; i < iters; ++i)
toHex3(i);
}
{
Timer t("static buffer");
for (size_t i = 0; i < iters; ++i)
toHex5(i);
}
}
|