Created
April 10, 2018 15:15
-
-
Save felipou/ad107bbb3a91814679beb22c0686fbeb to your computer and use it in GitHub Desktop.
C/C++ Datetime Format String Performance Tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Just compile with g++ datetime_format_string.cpp -std=c++11 | |
Tested on GCC 5.4.0 on Ubuntu 16.04 | |
*/ | |
#include <iostream> | |
#include <chrono> | |
#include <sys/time.h> | |
#include <stdio.h> | |
using namespace std; | |
using namespace chrono; | |
void func1() { | |
struct timeval current_time; | |
gettimeofday(¤t_time, 0); | |
char time_str[128]; | |
strftime(time_str, | |
sizeof(time_str), | |
"%F %T", localtime(¤t_time.tv_sec)); | |
cout << time_str << endl; | |
} | |
void func2() { | |
struct timeval current_time; | |
gettimeofday(¤t_time, 0); | |
char time_str_without_subseconds[128]; | |
strftime(time_str_without_subseconds, | |
sizeof(time_str_without_subseconds), | |
"%F %T.%%06ld", localtime(¤t_time.tv_sec)); | |
char time_str[128]; | |
sprintf(time_str, time_str_without_subseconds, | |
(long)current_time.tv_usec); | |
cout << time_str << endl; | |
} | |
void func3() { | |
struct timeval current_time; | |
gettimeofday(¤t_time, 0); | |
struct tm local_tm; | |
localtime_r(¤t_time.tv_sec, &local_tm); | |
char time_str[128]; | |
sprintf(time_str, "%04d-%02d-%02d %02d:%02d:%02d.%06ld", | |
local_tm.tm_year+1900, local_tm.tm_mon+1, | |
local_tm.tm_mday, local_tm.tm_hour, local_tm.tm_min, | |
local_tm.tm_sec, (long)current_time.tv_usec); | |
cout << time_str << endl; | |
} | |
int main() { | |
high_resolution_clock::time_point t1 = high_resolution_clock::now(); | |
for(int i = 0; i < 1000000; i += 1) { | |
func1(); | |
} | |
high_resolution_clock::time_point t2 = high_resolution_clock::now(); | |
for(int i = 0; i < 1000000; i += 1) { | |
func2(); | |
} | |
high_resolution_clock::time_point t3 = high_resolution_clock::now(); | |
for(int i = 0; i < 1000000; i += 1) { | |
func3(); | |
} | |
high_resolution_clock::time_point t4 = high_resolution_clock::now(); | |
auto duration1 = duration_cast<milliseconds>( t2 - t1 ).count(); | |
auto duration2 = duration_cast<milliseconds>( t3 - t2 ).count(); | |
auto duration3 = duration_cast<milliseconds>( t4 - t3 ).count(); | |
cerr << "duration strftime (ms): " << duration1 << endl; | |
cerr << "duration strftime with microseconds (ms): " << duration2 << endl; | |
cerr << "duration localtime_r with microseconds (ms): " << duration3 << endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on Ubuntu 16.04 with GCC 5.4.0 and Linux kernel 4.13.0