C-比较GPS时间戳的有效方法



我的目标是比较由GPS设备提供的两个U_long时间戳。像16290212这样的长整数具有以下结构:

hhmmssµµ

以下代码段显示了一种方法,如何将长整数解析为整数数组。但是我认为这不是很有效。比较两个时间戳的最快方法是什么?我很想使用Unix时间戳,但是在这种情况下是不可能的。

u_long timestamp_old = 16290212;
u_long base = 1000000;
/* arr[0]: hours
 * arr[1]: minutes
 * arr[2]: seconds
 * arr[3]: miliseconds */
int arr[4];
int i=0;
// parse timestamp_old
while(base >= 1)
{
    arr[i++] = (timestamp_old / base);
    timestamp_old = (timestamp_old % base);
    base /= 100;
}

您的时间戳是 u_longs;比较它们,就像比较任何2个 u_longs,例如 <

比较两个时间戳的最快方法是什么?
我想检查差异是否小于400 ms

也许不是最快,至少是一个快速最坏情况的起点。请注意,ssµµµµµµµµ相同。

int32_t GPS_to_ms(u_long timestamp) {
  int32_t ms = timestamp%100000;
  int32_t hhmm = timestamp / 100000;
  ms +=  (hhmm%100)*60*1000;
  int32_t hh = hhmm / 100;
  ms +=  hh*60*60*1000;
  return ms;
}
if (GPS_to_ms(timestamp_later) - GPS_to_ms(timestamp_first) < 400) {
  // timestamps are in close succession.
}

平均,1)假设timestamp_later >= timestamp_first加快速度通常是正确的2)时间戳通常具有相同的hhmm

bool GPS_compare_400(u_long first, u_long later) {
  int32_t ms1 = first%100000;
  int32_t hhmm1 = first/100000;
  int32_t ms2 = later%100000;
  int32_t hhmm2 = later/100000;
  if (hhmm1 == hhmm2) {
    return ms2 - ms1 < 400;
  }
  return GPS_to_ms(timestamp_later) - GPS_to_ms(timestamp_first) < 400;
}

我假设输入是" hhmmssμµ"形式的字符串gpstime。我认为始终存在尾随的零,因此微秒部分总是有三位数字。

1。

int h, m, s, us;
double t;
if(sscanf(gpstime, "%2d%2d%2d%3d", &h, &m, &s, &us) == 4)
    t = (h * 60L + m) * 60 + s + us/1000.;
else {
    /* parse error */
    t = 0;
}

如果这还不够高效,这里有些偏低,避开scanf

2。

#define Ctod(c) ((c) - '0')
int h = 10 * Ctod(utctime[0]) + Ctod(utctime[1]);
int m = 10 * Ctod(utctime[2]) + Ctod(utctime[3]);
int s = 10 * Ctod(utctime[4]) + Ctod(utctime[5]);
int us = 100 * Ctod(utctime[6]) + 10 * Ctod(utctime[7]) + Ctod(utctime[8]);
double t = (h * 60L + m) * 60 + s + us/1000.;

无论哪种情况,一旦获得t值,就可以按照往常来进行比较。

如果您不想使用浮点,请将t更改为long int,请根据适当更改缩放因子,并将您的最终差异与400而不是0.4

(但随之而来的是,我不必担心效率太多。对可怜的人来说,10 Hz听起来很快,但是十分之一的一秒钟对于一台体面的计算机来说是很长一段时间的地狱。)

最新更新