Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i stop a while loop after a certain time in C

Tags:

c

How do i stop a while loop after a certain time in C, i did it in c++ and i tried converting that to c (below) but it didnt work

#include <time.h>

int main(void)
{
    time_t endwait;
    time_t start;

    endwait = start + seconds ;
    while (start < endwait)
    {
        /* Do stuff while waiting */
    }
}
like image 768
user2976568 Avatar asked Sep 17 '25 09:09

user2976568


1 Answers

In C, there are no constructors, so time_t start; just declares a variable of type time_t. It does not set that equal to the current time. You thus need to read the current time before the loop (and assign that to starttime), and read it within the loop (or within the while condition).

Also, the loop should be

while ((currenttime = [code to assign time]) < endwait)
{
    ...
}

or neater

while ([code to assign time] < endwait)
{
    ...
}

IE look at currenttime, not starttime.

In order to read the time, you want to use time(NULL) (if you are using time values in seconds. So your completed program would look something like (untested):

#include <time.h>

int main(void)
{
    time_t endwait;
    int seconds = 123;

    endwait = time (NULL) + seconds ;
    while (time (NULL) < endwait)
    {
        /* Do stuff while waiting */
    }
}

Note also that if the number of seconds is small, you might want to use the higher precision gettimeofday. This will prevent waiting for 1 second waiting for anything from 0 seconds to 1.

like image 189
abligh Avatar answered Sep 18 '25 22:09

abligh