Search code examples
c++datedatetimemktimec++20

Fast way to transform datetime strings with timezones into UNIX timestamps in C++


I want to convert a huge file containing datetime strings to seconds since UNIX epoch (January 1, 1970) in C++. I need the computation to be very fast because I need to handle large amount of datetimes.

So far I've tried two options. The first was to use mktime, defined in time.h. The second option I tried was Howard Hinnant's date library with time zone extension.

Here is the code I used to compare the performance between mktime and Howard Hinnant's tz:

for( int i=0; i<RUNS; i++){
    genrandomdate(&time_str);

    time_t t = mktime(&time_str);

}

auto tz = current_zone()
for( int i=0; i<RUNS; i++){

    genrandomdate(&time_str);
    auto ymd = year{time_str.tm_year+1900}/(time_str.tm_mon+1)/time_str.tm_mday;
    auto tcurr = make_zoned(tz, local_days{ymd} + 
            seconds{time_str.tm_hour*3600 + time_str.tm_min*60 + time_str.tm_sec}, choose::earliest);
    auto tbase = make_zoned("UTC", local_days{January/1/1970});
    auto dp = tcurr.get_sys_time() - tbase.get_sys_time() + 0s;

}

The results of the comparison:

time for mktime : 0.000142s
time for tz : 0.018748s

The performance of tz is not good compared to mktime. I want something faster than mktime because mktime is also very slow when used repeatedly for large number iterations. Java Calendar provides a very fast way to do this, but I don't know any C++ alternatives for this when time zones are also in play.

Note: Howard Hinnant's date works very fast (even surpassing Java) when used without time zones. But that is not enough for my requirements.


Solution

  • I found that Google's CCTZ can do the same thing.