如何在C中使用计时器?

时间:2013-06-18 11:42:44

标签: c timer countdowntimer

在C中使用计时器的方法是什么?我需要等到500毫秒才能找到工作。请提及做这项工作的任何好方法。我使用sleep(3);但是这个方法在那段时间内没有做任何工作。我有一些东西会在那个时候尝试获得任何输入。

4 个答案:

答案 0 :(得分:9)

这是我使用的解决方案(需要#include <time.h>):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
  /*
   * Do something to busy the CPU just here while you drink a coffee
   * Be sure this code will not take more than `trigger` ms
   */

  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
  msec/1000, msec%1000, iterations);

答案 1 :(得分:8)

您可以使用 time.h 中的time_t结构和clock()函数。

使用time_t将开始时间存储在clock()结构中,并通过比较存储时间和当前时间之间的差异来检查已用时间。

答案 2 :(得分:2)

可能这个例子对你有帮助

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


/*
    Implementation simple timeout

    Input: count milliseconds as number

    Usage:
        setTimeout(1000) - timeout on 1 second
        setTimeout(10100) - timeout on 10 seconds and 100 milliseconds
 */
void setTimeout(int milliseconds)
{
    // If milliseconds is less or equal to 0
    // will be simple return from function without throw error
    if (milliseconds <= 0) {
        fprintf(stderr, "Count milliseconds for timeout is less or equal to 0\n");
        return;
    }

    // a current time of milliseconds
    int milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;

    // needed count milliseconds of return from this timeout
    int end = milliseconds_since + milliseconds;

    // wait while until needed time comes
    do {
        milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;
    } while (milliseconds_since <= end);
}


int main()
{

    // input from user for time of delay in seconds
    int delay;
    printf("Enter delay: ");
    scanf("%d", &delay);

    // counter downtime for run a rocket while the delay with more 0
    do {
        // erase the previous line and display remain of the delay
        printf("\033[ATime left for run rocket: %d\n", delay);

        // a timeout for display
        setTimeout(1000);

        // decrease the delay to 1
        delay--;

    } while (delay >= 0);

    // a string for display rocket
    char rocket[3] = "-->";

    // a string for display all trace of the rocket and the rocket itself
    char *rocket_trace = (char *) malloc(100 * sizeof(char));

    // display trace of the rocket from a start to the end
    int i;
    char passed_way[100] = "";
    for (i = 0; i <= 50; i++) {
        setTimeout(25);
        sprintf(rocket_trace, "%s%s", passed_way, rocket);
        passed_way[i] = ' ';
        printf("\033[A");
        printf("| %s\n", rocket_trace);
    }

    // erase a line and write a new line
    printf("\033[A");
    printf("\033[2K");
    puts("Good luck!");

    return 0;
}

编译文件,运行并删除(我的偏好)

$ gcc timeout.c -o timeout && ./timeout && rm timeout

尝试自己运行以查看结果。

注意:

测试环境

$ uname -a
Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
$ gcc --version
gcc (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

答案 3 :(得分:2)

是的,您需要循环。如果您已经有一个主循环(大多数GUI事件驱动的东西都有),那么您可以将计时器加入其中。使用:

#include <time.h> 
time_t my_t, fire_t;

然后(超过1秒),通过读取当前时间来初始化计时器:

my_t = time(NULL);

添加您的计时器应等待的秒数,并将其存储在fire_t中。 time_t本质上是uint32_t,您可能需要强制转换。

在循环中执行另一次

my_t = time(NULL);

如果(my_t> fire_t),则考虑触发计时器并在其中执行所需的操作。这可能包括通过下次执行另一个fire_t = time(NULL)+ seconds_to_wait来重置它。

time_t是一种有点过时的unix方法,用于存储时间(自1970年1月1日午夜以来的秒数),但是它具有许多优点。对于小于1秒的时间,您需要使用gettimeofday()(微秒)或clock_gettime()(纳秒)并处理struct timeval或struct timespec,它是time_t以及自该1秒标记以来的微秒或纳秒。设置计时器的工作方式相同,除了增加等待时间之外,如果生成的微秒或纳秒值超过1秒,则需要记住手动进行进位(进入time_t)。是的,很乱。看到男人2时间,男人gettimeofday,男人clock_gettime。

sleep(),usleep(),nanosleep()有一个隐藏的好处。您将其视为暂停程序,但是他们真正要做的是在这段时间内释放CPU。通过读取时间并与完成时间进行比较来反复轮询(我们还在那里吗?)将消耗大量CPU周期,这可能会减慢同一计算机上运行的其他程序的速度(并消耗更多的电量/电池)。最好在大多数时间都sleep()然后开始检查时间。

如果您想睡觉同时工作,则需要线程。