getdatetimestr

下午写了这么一个函数

char* getdatetimestr() {
    static char datetimestr[32] = {0};
    static time_t last_update_time = 0;
    struct timeval tv = {0};
    gettimeofday(&tv, NULL);
    time_t nowtime = tv.tv_sec;
    if (nowtime != last_update_time) {
        last_update_time = nowtime;
        struct tm nowtm = {0};
        localtime_r(&nowtime, &nowtm);
        strftime(datetimestr, sizeof(datetimestr), "%Y-%m-%d %H:%M:%S", &nowtm);
    }
    snprintf(datetimestr+19, sizeof(datetimestr)-19, ".%06ld", tv.tv_usec);
    return datetimestr;
}

返回的串类似 2015-07-17 18:51:06.709628

注意到其中有一个缓存的机制,对于同一秒的时间单位内,只格式化微秒的部分,复用秒和秒以左的字符串,这个优化的差别有多大呢,实测下来,在同一个机器上,不用这个优化,每秒大约 5 万次,用了这个优化,每秒大约 50 万次。

Leave a Reply

Your email address will not be published. Required fields are marked *