2013-06-18 3 views
5

Что такое метод использования таймера в C? Мне нужно подождать до 500 мс для работы. Пожалуйста, укажите хороший способ выполнить эту работу. Я использовал sleep(3); Но этот метод не выполняет никакой работы за это время. У меня есть что-то, что попытается до этого времени получить какой-либо ввод.Как использовать таймер в C?

+0

выберите, опрос, Epoll ... Что вы хотите? –

+1

Это дублированный вопрос. См. Http://stackoverflow.com/questions/459691/best-timing-method-in-c – pcbabu

+1

@Eddy_Em что это за выбор, опрос, epoll? Я хочу установить таймер на 5 секунд. Если пользовательский ввод в течение этого времени, вход будет принят как действительный. –

ответ

4

Вы можете использовать функцию time_t и функцию clock() от time.h.

Сохраните время начала в структуре time_t с помощью clock() и проверьте прошедшее время, сравнив разницу между сохраненным временем и текущим временем.

+0

Должно ли оно находиться внутри циклов? –

+1

Это зависит от того, что вы хотите сделать. Если ваша программа основана на большой петле, вы можете поместить ее внутрь. В противном случае вам нужно будет создать выделенный поток для цикла на вашем таймере. – Qutus

4

Вот решение, которое я использовал (требуется #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); 
0

Может быть это примеры помогут вам

#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; 
} 

Compile файл, запускать и удалять после (мои предпочтения)

$ 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. 
Смежные вопросы