我正在寻找确定 NTP 时间戳 vector 的日期组件的最快方法。
本例中的输入是 NTP 时间戳或自 1900-01-01 以来测量的秒数,通过添加 2208988800 或减去(如果采用其他方式)来往返 Unix 时间很简单。我需要将时间戳分解为其他 API 的日期组件,这些 API 只接受日期作为其组件,特别是年、月和日。
使用 time.h
(glibc
) 中的 ANSI C 方法,我可以轻松导出组件,但对于较大的 vector 来说太慢了。较小的 vector 可能包含 172800 个值,但更现实的是,我希望能够尽快处理具有 1314000 个值的 vector 。
我在想,我可以自己压缩时间,并通过迭代地减去每个日期组件的二除数输入的时间戳,直到我到达日期,从而消除少量的 glibc 开销,本质上glibc 做什么,但没有时区和一些额外的(小)开销。
我很快发现这样做仍然很慢。
我正在处理这样的事情:
typedef struct simple_time_ {
int year;
int month;
int day;
} simple_time;
size_t time_cruncher(const time_t *ntp_vector, simple_time *out, size_t len)
{
size_t i;
time_t corrected;
struct tm cal;
for(i=0;i<len;i++) {
corrected = ntp_vector[i] - 2208988800; /* NTP Offset */
gmtime_r(&corrected, &cal);
simple_time[i].year = cal.tm_year + 1900;
simple_time[i].month = cal.tm_mon + 1;
simple_time[i].day = cal.tm_mday;
}
return i;
}
是否有隐藏的算法可以帮助我更快地进行计算?类似于 Zeller 的算法,但从几秒钟到组件的日期?
谢谢!
最佳答案
鉴于您的许多连续时间戳很可能都在同一个月,请充分利用这一点。
Pseudo code
1) Calculate the y,m,d for the given timestamp 't' as you have above.
2) now calculate the t0 = gmtime(y, m, 1) and t1 = gmtime(y, m+1, 1). (Dec + 1 is OK)
3) As long as your timestamps are t0 <= t < t1, a simple add/divide is need to determine the day of the month.
4) Should 't' fall outside the range, go to step 1.
还可以确定当天的开始和结束时间,看看这是否适用于下一个时间戳。
关于c - 从秒开始的快速时间结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17352006/