使用time和difftime创建超时

ant*_*009 1 c

gcc (GCC) 4.6.0 20110419 (Red Hat 4.6.0-5)
Run Code Online (Sandbox Code Playgroud)

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

我的功能是为现有硬件创建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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将调用的函数将是这样的.

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;
}
Run Code Online (Sandbox Code Playgroud)

===============编辑更新结果==================

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
Run Code Online (Sandbox Code Playgroud)

Mar*_*rio 5

你过度复杂了 - 简化:

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

time_t通常只是一个int或long int取决于您的平台计算自1970年1月1日以来的秒数.

边注:

int timeout = timeout_ms / 1000;
Run Code Online (Sandbox Code Playgroud)

一秒钟由1000毫秒组成.

编辑-另注:你最有可能,以确保其他线程(S)和/或事件处理可能发生的,所以包括某种线程闲置(使用sleep(),nanosleep()或其他).