使用time和difftime创建超时

时间:2011-04-29 19:04:35

标签: c

gcc (GCC) 4.6.0 20110419 (Red Hat 4.6.0-5)

我正在努力获得开始和结束时间。并获得它们之间的差异。

我的功能是为现有硬件创建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

2 个答案:

答案 0 :(得分:5)

你过度复杂了 - 简化:

time_t start = time();
for (;;) {
    // try something
    if (time() > start + 5) {
        printf("5s timeout!\n");
        break;
    }
}

time_t通常应该是intlong int,具体取决于您的平台计算自1970年1月1日以来的秒数。

旁注:

int timeout = timeout_ms / 1000;

一秒钟由1000毫秒组成。

编辑 - 另一个说明: 您很可能必须确保其他线程和/或事件处理可能发生,因此包括某种线程不活动(使用sleep()nanosleep()或其他)。

答案 1 :(得分:1)

不调用Sleep()函数这是一个非常糟糕的设计:你的循环将使用100%的CPU。即使您使用线程,您的其他线程也没有太多时间运行,因为此线程将使用许多CPU周期。 你应该设计类似的东西:

while(true) {
  Sleep(100); // lets say you want a precision of 100 ms
  // Do the compare time stuff here
}

如果您需要精确定时并使用不同的线程/进程,请使用互斥锁(semaphores,递增/递减为1)或关键部分,以确保您的函数的时间比较不会被中断你自己的另一个进程/线程。 我相信您的红帽是System V,因此您可以使用IPC

进行同步