如何使用clock_gettime制作精确的倒数计时器?

时间:2012-12-16 19:20:09

标签: c linux time

有人可以在Linux下解释如何使用clock_gettime制作倒数计时器。我知道你可以使用clock()函数来获取cpu时间,并将它乘以CLOCKS_PER_SEC来获得实际时间,但是我告诉clock()函数不适合这个。

到目前为止,我已尝试过这种情况(十亿人暂停一秒钟)

#include <stdio.h>
#include <time.h>

#define BILLION 1000000000

int main()
{
 struct timespec rawtime;
 clock_gettime(CLOCK_MONOTONIC_RAW, &rawtime);
 unsigned long int current =  ( rawtime.tv_sec + rawtime.tv_nsec );
 unsigned long int end =  (( rawtime.tv_sec + rawtime.tv_nsec ) + BILLION );
 while ( current < end )
 {
  clock_gettime(CLOCK_MONOTONIC_RAW, &rawtime);
  current =  ( rawtime.tv_sec + rawtime.tv_nsec );
 }

 return 0;
}

我知道这本身并不是很有用,但是一旦我发现如何正确计时,我就可以在我的项目中使用它。我知道sleep()可以用于此目的,但我想自己编写计时器,以便我可以更好地将它集成到我的项目中 - 例如它返回剩余时间的可能性,而不是暂停整个程序

2 个答案:

答案 0 :(得分:5)

请不要那样做。您在busy loop中没有任何内容消耗CPU功率。

为什么不使用nanosleep()功能呢?它非常适合您概述的用例。或者,如果你想要一个更简单的界面,也许像

#define _POSIX_C_SOURCE 200809L
#include <time.h>
#include <errno.h>

/* Sleep for the specified number of seconds,
 * and return the time left over.
*/
double dsleep(const double seconds)
{
    struct timespec  req, rem;

    /* No sleep? */
    if (seconds <= 0.0)
        return 0.0;

    /* Convert to seconds and nanoseconds. */
    req.tv_sec = (time_t)seconds;
    req.tv_nsec = (long)((seconds - (double)req.tv_sec) * 1000000000.0);

    /* Take care of any rounding errors. */
    if (req.tv_nsec < 0L)
        req.tv_nsec = 0L;
    else
    if (req.tv_nsec > 999999999L)
        req.tv_nsec = 999999999L;

    /* Do the nanosleep. */
    if (nanosleep(&req, &rem) != -1)
        return 0.0;

    /* Error? */
    if (errno != EINTR)
        return 0.0;

    /* Return remainder. */
    return (double)rem.tv_sec + (double)rem.tv_nsec / 1000000000.0;
}

不同之处在于使用这个CPU可以自由地做其他事情,而不是像疯狂的松鼠那样旋转。

答案 1 :(得分:2)

这不是一个答案,而是一个如何使用信号和POSIX计时器来实现超时计时器的例子;旨在回应OP的后续问题,对已接受的答案进行评论。

#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>

/* Timeout timer.
*/
static timer_t                  timeout_timer;
static volatile sig_atomic_t    timeout_state = 0;
static volatile sig_atomic_t    timeout_armed = 2;
static const int                timeout_signo = SIGALRM;

#define TIMEDOUT() (timeout_state != 0)

/* Timeout signal handler.
*/
static void timeout_handler(int signo, siginfo_t *info, void *context __attribute__((unused)))
{
    if (timeout_armed == 1)
        if (signo == timeout_signo && info && info->si_code == SI_TIMER)
            timeout_state = ~0;
}

/* Unset timeout.
 * Returns nonzero if timeout had expired, zero otherwise.
*/
static int timeout_unset(void)
{
    struct itimerspec   t;   
    const int           retval = timeout_state;

    /* Not armed? */
    if (timeout_armed != 1)
        return retval;

    /* Disarm. */
    t.it_value.tv_sec = 0;
    t.it_value.tv_nsec = 0;
    t.it_interval.tv_sec = 0;
    t.it_interval.tv_nsec = 0;
    timer_settime(timeout_timer, 0, &t, NULL);

    return retval;
}

/* Set timeout (in wall clock seconds).
 * Cancels any pending timeouts.
*/
static int timeout_set(const double seconds)
{
    struct itimerspec  t;

    /* Uninitialized yet? */
    if (timeout_armed == 2) {
        struct sigaction    act;
        struct sigevent     evt;

        /* Use timeout_handler() for timeout_signo signal. */
        sigemptyset(&act.sa_mask);
        act.sa_sigaction = timeout_handler;
        act.sa_flags = SA_SIGINFO;

        if (sigaction(timeout_signo, &act, NULL) == -1)
            return errno;

        /* Create a monotonic timer, delivering timeout_signo signal. */
        evt.sigev_value.sival_ptr = NULL;
        evt.sigev_signo = timeout_signo;
        evt.sigev_notify = SIGEV_SIGNAL;

        if (timer_create(CLOCK_MONOTONIC, &evt, &timeout_timer) == -1)
            return errno;

        /* Timeout is initialzied but unarmed. */
        timeout_armed = 0;
    }

    /* Disarm timer, if armed. */
    if (timeout_armed == 1) {

        /* Set zero timeout, disarming the timer. */
        t.it_value.tv_sec = 0;
        t.it_value.tv_nsec = 0;
        t.it_interval.tv_sec = 0;
        t.it_interval.tv_nsec = 0;

        if (timer_settime(timeout_timer, 0, &t, NULL) == -1)
            return errno;

        timeout_armed = 0;
    }

    /* Clear timeout state. It should be safe (no pending signals). */
    timeout_state = 0;

    /* Invalid timeout? */
    if (seconds <= 0.0)
        return errno = EINVAL;

    /* Set new timeout. Check for underflow/overflow. */
    t.it_value.tv_sec = (time_t)seconds;
    t.it_value.tv_nsec = (long)((seconds - (double)t.it_value.tv_sec) * 1000000000.0);
    if (t.it_value.tv_nsec < 0L)
        t.it_value.tv_nsec = 0L;
    else
    if (t.it_value.tv_nsec > 999999999L)
        t.it_value.tv_nsec = 999999999L;

    /* Set it repeat once every millisecond, just in case the initial
     * interrupt is missed. */
    t.it_interval.tv_sec = 0;
    t.it_interval.tv_nsec = 1000000L;

    if (timer_settime(timeout_timer, 0, &t, NULL) == -1)
        return errno;

    timeout_armed = 1;

    return 0;
}


int main(void)
{
    char    *line = NULL;
    size_t   size = 0;
    ssize_t  len;

    fprintf(stderr, "Please supply input. The program will exit automatically if\n");
    fprintf(stderr, "it takes more than five seconds for the next line to arrive.\n");
    fflush(stderr);

    while (1) {

        if (timeout_set(5.0)) {
            const char *const errmsg = strerror(errno);
            fprintf(stderr, "Cannot set timeout: %s.\n", errmsg);
            return 1;
        }

        len = getline(&line, &size, stdin);
        if (len == (ssize_t)-1)
            break;

        if (len < (ssize_t)1) {
            /* This should never occur (except for -1, of course). */
            errno = EIO;
            break;
        }

        /* We do not want *output* to be interrupted,
         * so we cancel the timeout. */
        timeout_unset();

        if (fwrite(line, (size_t)len, 1, stdout) != 1) {
            fprintf(stderr, "Error writing to standard output.\n");
            fflush(stderr);
            return 1;
        }
        fflush(stdout);

        /* Next line. */
    }

    /* Remember to cancel the timeout. Also check it. */
    if (timeout_unset())
        fprintf(stderr, "Timed out.\n");
    else
    if (ferror(stdin) || !feof(stdin))
        fprintf(stderr, "Error reading standard input.\n");
    else
        fprintf(stderr, "End of input.\n");

    fflush(stderr);

    /* Free line buffer. */
    free(line);
    line = NULL;
    size = 0;

    /* Done. */
    return 0;
}

如果将上述内容保存为timer.c,则可以使用例如

进行编译
gcc -W -Wall -O3 -std=c99 -pedantic timer.c -lrt -o timer

并使用./timer运行它。

如果你仔细阅读上面的代码,你会发现它实际上是一个周期性的定时器信号(以毫秒为间隔),在第一个信号之前有一个可变的延迟。这只是我喜欢使用的技术,以确保我不会错过信号。 (信号重复,直到超时未设置。)

请注意,尽管您可以在信号处理程序中进行计算,但您应该只使用 async-signal-safe 的函数;见man 7 signal。此外,只有sig_atomic_t类型是原子wrt。普通的单线程代码和信号处理程序。因此,最好只使用信号作为指标,并在您自己的程序中执行实际代码。

如果你想要,例如在信号处理程序中更新怪物坐标,这可能有点棘手。我使用三个包含怪物信息的数组,并使用GCC __sync_bool_compare_and_swap()更新数组指针 - 与图形中的三重缓冲技术非常相似。

如果您需要多个并发超时,则可以使用多个计时器(其中有多个可用),但最佳选择是定义超时时隙。 (您可以使用生成计数器来检测“遗忘”超时等等。)每当设置或取消设置新超时时,您都会更新超时以反映下一个超时的超时。这是更多的代码,但实际上是对上述内容的直接扩展。