【发布时间】:2010-01-04 14:03:19
【问题描述】:
我正在为 i2c 总线操作使用开源库。这个库经常使用一个函数来获得一个毫秒分辨率的实际时间戳。
示例调用:
nowtime = timer_nowtime();
while ((i2c_CheckBit(dev) == true) && ((timer_nowtime() - nowtime) < I2C_TIMEOUT));
使用这个 i2c 库的应用程序会占用大量 CPU 容量。我发现,运行的程序最多调用函数timer_nowtime()。
原函数:
unsigned long timer_nowtime(void) {
static bool usetimer = false;
static unsigned long long inittime;
struct tms cputime;
if (usetimer == false)
{
inittime = (unsigned long long)times(&cputime);
usetimer = true;
}
return (unsigned long)((times(&cputime) - inittime)*1000UL/sysconf(_SC_CLK_TCK));
}
我现在的目标是,提高这个功能的效率。我是这样尝试的:
struct timespec systemtime;
clock_gettime(CLOCK_REALTIME, &systemtime);
//convert the to milliseconds timestamp
// incorrect way, because (1 / 1000000UL) always returns 0 -> thanks Pace
//return (unsigned long) ( (systemtime.tv_sec * 1000UL) + (systemtime.tv_nsec
// * (1 / 1000000UL)));
return (unsigned long) ((systemtime.tv_sec * 1000UL)
+ (systemtime.tv_nsec / 1000000UL));
不幸的是,我不能声明这个函数inline(不知道为什么)。
哪种方法更有效地获取毫秒分辨率的实际时间戳? 我确信有一种更高效的方式来做到这一点。有什么建议么?
谢谢。
【问题讨论】:
-
不是 (1 / 1000000UL) 总是返回 0 吗?
-
佩斯,你是对的。 (1 / 1000000UL)= 0;我会更正我的代码。