Skip to content

Instantly share code, notes, and snippets.

@daverigby
Last active November 22, 2017 11:02
Show Gist options
  • Save daverigby/63983da5a15a981f90a8fe0e20347b0e to your computer and use it in GitHub Desktop.
Save daverigby/63983da5a15a981f90a8fe0e20347b0e to your computer and use it in GitHub Desktop.
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <iostream>
#include <vector>
#include "date.h" // From https://github.com/HowardHinnant/date/blob/master/include/date/date.h
static constexpr const size_t magnitude_bits = 4;
union VariablePrecision {
struct {
uint16_t precision : 16 - magnitude_bits;
uint16_t magnitude : magnitude_bits;
} fields;
uint16_t raw;
};
std::chrono::microseconds decode(VariablePrecision p) {
auto count = uint64_t(1 + p.fields.precision) << uint64_t(p.fields.magnitude);
return std::chrono::microseconds(count);
}
int main() {
auto min = std::chrono::microseconds::max();
auto max = std::chrono::microseconds::min();
std::vector<std::chrono::microseconds> vec;
for (uint16_t i = std::numeric_limits<uint16_t>::min();
i < std::numeric_limits<uint16_t>::max();
++i) {
VariablePrecision p;
p.raw = i;
auto decoded = decode(p);
vec.emplace_back(decoded);
if (decoded < min) {
min = decoded;
}
if (decoded > max) {
max = decoded;
}
}
std::sort(vec.begin(), vec.end());
for (const auto& v : vec) {
std::cout << date::make_time(v) << "\n";
}
std::cout << "min:" << date::make_time(min) << " max:" << date::make_time(max) << "\n";
}
@daverigby
Copy link
Author

With 4 magnitude bits gives range of 1 microsecond to 2m14s:

min:00:00:00.000001 max:00:02:14.184960

With 5 magnitude bits, max increases to 1221 hours (50+ days), which is probably a bigger range than necessary:

min:00:00:00.000001 max:1221:04:59.027456

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