C语言 如何在C中使用计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17167949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:43:03  来源:igfitidea点击:

How to use timer in C?

ctimercountdowntimer

提问by David Guyon

What is the method to use a timer in C? I need to wait until 500 ms for a job. Please mention any good way to do this job. I used sleep(3);But this method does not do any work in that time duration. I have something that will try until that time to get any input.

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

采纳答案by Qutus

You can use a time_tstruct and clock()function from time.h.

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

Store the start time in a time_tstruct by using clock()and check the elapsed time by comparing the difference between stored time and current time.

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

回答by David Guyon

Here's a solution I used (it needs #include <time.h>):

这是我使用的解决方案(它需要#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);

回答by PADYMKO

May be this examples help to you

可能这个例子对你有帮助

#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("3[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("3[A");
        printf("| %s\n", rocket_trace);
    }

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

    return 0;
}

Compile file, run and delete after (my preference)

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

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

Try run it for yourself to see result.

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

Notes:

笔记:

Testing environment

测试环境

$ 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.

回答by Alan Corey

Yes, you need a loop. If you already have a main loop (most GUI event-driven stuff does) you can probably stick your timer into that. Use:

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

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

Then (for times over 1 second), initialize your timer by reading the current time:

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

my_t = time(NULL);

Add the number of seconds your timer should wait and store it in fire_t. A time_t is essentially a uint32_t, you may need to cast it.

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

Inside your loop do another

在你的循环中做另一个

my_t = time(NULL);

if (my_t > fire_t) then consider the timer fired and do the stuff you want there. That will probably include resetting it by doing another fire_t = time(NULL) + seconds_to_wait for next time.

if (my_t > fire_t) 然后考虑定时器被触发并在那里做你想做的事情。这可能包括通过为下次执行另一个 fire_t = time(NULL) + seconds_to_wait 来重置它。

A time_t is a somewhat antiquated unix method of storing time as the number of seconds since midnight 1/1/1970 but it has many advantages. For times less than 1 second you need to use gettimeofday() (microseconds) or clock_gettime() (nanoseconds) and deal with a struct timeval or struct timespec which is a time_t and the microseconds or nanoseconds since that 1 second mark. Making a timer works the same way except when you add your time to wait you need to remember to manually do the carry (into the time_t) if the resulting microseconds or nanoseconds value goes over 1 second. Yes, it's messy. See man 2 time, man gettimeofday, man clock_gettime.

time_t 是一种有点过时的 unix 方法,用于将时间存储为自 1970 年 1 月 1 日午夜以来的秒数,但它有许多优点。对于小于 1 秒的时间,您需要使用 gettimeofday()(微秒)或 clock_gettime()(纳秒)并处理一个 struct timeval 或 struct timespec,它是 time_t 和自 1 秒标记以来的微秒或纳秒。制作计时器的工作方式相同,除了当您添加等待时间时,如果结果微秒或纳秒值超过 1 秒,您需要记住手动进行进位(进入 time_t)。是的,很乱。参见 man 2 time、man gettimeofday、man clock_gettime。

sleep(), usleep(), nanosleep() have a hidden benefit. You see it as pausing your program, but what they really do is release the CPU for that amount of time. Repeatedly polling by reading the time and comparing to the done time (are we there yet?) will burn a lot of CPU cycles which may slow down other programs running on the same machine (and use more electricity/battery). It's better to sleep() most of the time then start checking the time.

sleep(), usleep(), nanosleep() 有一个隐藏的好处。你认为它暂停了你的程序,但他们真正做的是在这段时间内释放 CPU。通过读取时间并与完成时间进行比较来反复轮询(我们到了吗?)会消耗大量 CPU 周期,这可能会减慢同一台机器上运行的其他程序的速度(并使用更多电力/电池)。最好在大部分时间 sleep() 然后开始检查时间。

If you're trying to sleep and do work at the same time you need threads.

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