quill
|
A class that converts a timestamp to a string based on the given format. More...
#include <StringFromTime.h>
Public Member Functions | |
QUILL_ATTRIBUTE_COLD void | init (std::string timestamp_format, Timezone timezone) |
QUILL_NODISCARD QUILL_ATTRIBUTE_HOT std::string const & | format_timestamp (time_t timestamp) |
Protected Types | |
enum | format_type : uint8_t { H, M, S, I, k, l, s } |
Protected Member Functions | |
QUILL_ATTRIBUTE_COLD void | _populate_initial_parts (std::string timestamp_format) |
void | _populate_pre_formatted_string_and_cached_indexes (time_t timestamp) |
A class that converts a timestamp to a string based on the given format.
It works exactly the same as strftime() but it caches the string on it's creation and only modifies the parts of the string that need to change. This is much more efficient than calling strftime as we just need to calculate the different between the cached and the requested timestamp and modify our preformatted string.
1) We take a format string eg "%Y-%m-%dT%H:%M:%SZ". 2) We split it into several parts (_initial_parts) where we separate the time modifiers. e.g "%Y-%m-%dT", "%H", ":", "%M", ":", "%S", Z". 3) We cache the current timestamp and current h/m/s in seconds and on each part above we call strftime() and we create a preformatted string. 4) While calling stftime in 3) we can manually check for any time modifiers and store their index in the final pre-formatted string. 5) Next time we want to calculate the timestamp we will just calculate the difference in seconds between the current and the cache timestamp. Then we add this value to the cached seconds and then convert the seconds to hh::mm::ss and replace in our pre-formatted string using the stored indexes. 6) We re-calculate the pre-formatted string every midnight and noon.