增加这个功能的性能?

时间:2014-11-27 22:56:57

标签: c++

有没有办法避免在以下代码中对gmtime()进行如此多的调用:

unsigned int get_day(unsigned int timestamp)
{
    time_t t = timestamp;
    struct tm * timeval = gmtime(&t);
    return timeval->tm_wday;//0 = sun
}

unsigned int get_start_of_day(unsigned int timestamp)
{
    int day_of_w = get_day(timestamp);
    while(get_day(timestamp-3600) == day_of_w) timestamp -= 3600;
    while(get_day(timestamp-60) == day_of_w) timestamp -= 60;
    while(get_day(timestamp-1) == day_of_w) timestamp--;

    return timestamp;
}

1 个答案:

答案 0 :(得分:0)

或许这样吗?

time_t get_start_of_day(time_t timestamp)
{
    // convert timestamp to tm*
    struct tm* my_tm = gmtime(&timestamp);

    // zero out fractions of a day. 
    // gmtime returns a pointer to mutable struct
    my_tm->tm_sec = 0;
    my_tm->tm_min = 0;
    my_tm->tm_hour = 0;

    // convert back to timestamp
    timestamp = mktime(my_tm);
    return timestamp;
}