gcc (GCC) 4.6.0 20110419 (Red Hat 4.6.0-5)
我想获取开始和结束时间的时间。并获得它们之间的差异。使用时间和difftime创建超时
我有的功能是为我们现有的硬件创建一个API。
API wait_events带有一个以毫秒为单位的时间参数。所以我想在while循环之前开始。并用时间来获得秒数。然后,循环的1次迭代获得时间差,然后将该差异与超时进行比较。
非常感谢您的任何建议,
/* Wait for an event up to a specified time out.
* If an event occurs before the time out return 0
* If an event timeouts out before an event return -1 */
int wait_events(int timeout_ms)
{
time_t start = 0;
time_t end = 0;
double time_diff = 0;
/* convert to seconds */
int timeout = timeout_ms/100;
/* Get the initial time */
start = time(NULL);
while(TRUE) {
if(open_device_flag == TRUE) {
device_evt.event_id = EVENT_DEV_OPEN;
return TRUE;
}
/* Get the end time after each iteration */
end = time(NULL);
/* Get the difference between times */
time_diff = difftime(start, end);
if(time_diff > timeout) {
/* timed out before getting an event */
return FALSE;
}
}
}
,将调用会是这样的功能。
int main(void)
{
#define TIMEOUT 500 /* 1/2 sec */
while(TRUE) {
if(wait_events(TIMEOUT) != 0) {
/* Process incoming event */
printf("Event fired\n");
}
else {
printf("Event timed out\n");
}
}
return 0;
}
===============编辑与更新的结果==================
1) With no sleep -> 99.7% - 100% CPU
2) Setting usleep(10) -> 25% CPU
3) Setting usleep(100) -> 13% CPU
3) Setting usleep(1000) -> 2.6% CPU
4) Setting usleep(10000) -> 0.3 - 0.7% CPU
你好马里奥。这工作。谢谢。是的,这将是一个多线程应用程序。所以在我正在检查时间的while循环中。我应该在那里休息以暂停当前线程,以便其他线程可以发生。但是,如果这是多线程的话。无论如何,这些线程会发生,因为它们会在另一个线程中?你是这个意思吗?谢谢。 – ant2009 2011-04-29 19:52:15
他们应该(真的取决于您的操作系统的调度程序),但即使它闲置,您的应用程序仍将保持100%,这可能会减慢您等待的其他线程。如果你不想冒任何缓慢的风险,只需等待0毫秒。这听起来很愚蠢,但它会为操作系统提供一个方便的地方,即使您根本不在等待(在纸上),它也可以任务切换和处理事件。 – Mario 2011-04-29 20:31:47
你好马里奥,我更新了一些更新后的结果。你会说哪一个是最适合你的睡眠?谢谢。 – ant2009 2011-05-01 06:13:10