views:

192

answers:

8

Hi!

I don't know exactly how to word a search for this.. so I haven't had any luck finding anything.. :S

I need to implement a time delay in C.

for example I want to do some stuff, then wait say 1 minute, then continue on doing stuff.

Did that make sense? Can anyone help me out?

+6  A: 

Check sleep(3) man page or MSDN for Sleep

RC
A: 

Is it timer?

For WIN32 try http://msdn.microsoft.com/en-us/library/ms687012%28VS.85%29.aspx

ruslik
A: 

Try sleep(int number_of_seconds)

waffle paradox
A: 

sleep(int) works as a good delay. For a minute:

//Doing some stuff...
sleep(60); //Freeze for A minute
//Continue doing stuff...
thyrgle
+5  A: 

In standard C (C99), you can use time() to do this:

#include <time.h>
:
void waitFor (unsigned int secs) {
    retTime = time(0) + secs;     // Get finishing time.
    while (time(0) < retTime);    // Loop until it arrives.
}

By the way, this assumes time() returns a 1-second resolution value. I don't think that's mandated by the standard so you may have to adjust for it.


In order to clarify, this is the only way I'm aware of to do this with ISO C99 (and the question is tagged with nothing more than "C" which usually means portable solutions are desirable although, of course, vendor-specific solutions may still be given).

By all means, if you're on a platform that provides a more efficient way, use it. As several comments have indicated, there may be specific problems with a tight loop like this, with regard to CPU usage and battery life.

Any decent time-slicing OS would be able to drop the dynamic priority of a task that continuously uses its full time slice but the battery power may be more problematic.

However C specifies nothing about the OS details in a hosted environment, and this answer is for ISO C and ISO C alone (so no use of sleep, select, Win32 API calls or anything like that).

And keep in mind that POSIX sleep can be interrupted by signals. If you are going to go down that path, you need to do something like:

int finishing = 0; // set finishing in signal handler 
                   // if you want to really stop.

void sleepWrapper (unsigned int secs) {
    unsigned int left = secs;
    while ((left > 0) && (!finishing)) // Don't continue if signal has
        left = sleep (left);           //   indicated exit needed.
}
paxdiablo
what abt the cpu load?
SysAdmin
Yes, there will be a CPU load, but any decent OS (assuming pre-emptively multi-tasking) will detect that and drop the dynamic priority accordingly. And, if it's not, the CPU load doesn't matter (if it's co-operatively multitasked, you may want to look into a `yield` function). The reason I posted this is because there is no ISO-C portable way to do it and the question is tagged only "C" (`sleep`, while useful, is _not_ standard).
paxdiablo
@paxdiablo: No, actually it wont... The clock frequency of one of the CPUs will rise to 100% percent. And the CPU load matters, especially if you're on a laptop, when the CPU is maxed up it generates heat, and heat shortens the computers lifetime. On an old stationary that does probably not matter, this is how windows handles it (en endless loop doing nothing when there is noting to do). I guess that today OSes uses advanced power saving techinques, but I know that the Linux kernel issued a hlt instruction, same did I when I was 12.
Frank
@paxdiablo: let `retTime` be of type `time_t`. What systems do you refer to? It will hit CPU hardly in any system. Doesn't it matter to you? Besides that, this is a typical task for the OS, not for the language.
jweyrich
sleep( sec ) is apparently a ISO/IEC 9945-1:1990 (POSIX 1) standard, it is just Microsoft that does their way while the rest of the world does one way...
Frank
@Frank, if you're saying Windows dynamic priority won't be adjusted, you're wrong. Threads that voluntarily relinquish the CPU have the dynamic priorities boosted. Those that are forced out after using their entire time slice have their priorities reduced (though not below their baseline, from memory). This will tend to favour well-behaved apps over others. You're right that it will still consume CPU but again, if you're on an OS that allows `sleep` to put your process in a waiting queue (and halts the CPU when only the idle task is running), use it. It's still not standard.
paxdiablo
@jweyrich, yes it will hit CPU hard. And there are situations where that doesn't matter (say embedded non-multitasking or even desktops with proper dynamic priority adjustments). See my comment to Frank. The question is tagged C with no mention of Linux or Windows. That's why I posted this answer, because it's the _only_ way I know of to achieve this with C alone. If you find something in C99 that states otherwise, I'll be happy to delete the answer.
paxdiablo
You did not read what I said?
Frank
Feel free to clarify, @Frank, but the only part of my comment that your answer "No, actually, it won't" seemed to made sense to, was the "any decent OS ..." bit.
paxdiablo
I have a really good OS, it is more than decent. And there usually isn't any misbehaving programs, except for Adobe Flash Player. Most people using my OS would complain to the author if s/hes program is misbehaving and maybe even send a patch or not use the program at all.
Frank
I'm not entirely sure what you're trying to say there, Frank, it seemed a bit incongruous to me. I'm not disparaging your choice of OS. If you'd like to point out exactly what text of mine your "No, actually, it won't" comment applied to, we can discuss it. I've already stated _why_ I posted this answer. If you don't find it useful in your (in my opinion, limited) concept of a C environment, feel free to vote it down, that's what the voting system is for, after all.
paxdiablo
"[...] any decent OS (assuming pre-emptively multi-tasking) will detect that and drop the dynamic priority accordingly. And, if it's not, the CPU load doesn't matter [...]" that is what I said "No, actually, it won't" on. And I've already voted it down. And I've already stated why the CPU load does matter. Not that it gets hot, it also drains power. Guess what? My laptops battery last longer since I throw Windows out the window. And I have all kind of 3D-desktop fx that probably drains their share. Battery still lasts longer.
Frank
@paxdiablo: I support the affirmation that there's no standard way, but IMHO the loop solution proposed in `waitFor` should never be used in any multitasking system that exposes wait/suspend mechanisms. I didn't downvote because the answer is not incorrect after all. It was just lacking informations that you included @ revision 4.
jweyrich
@Frank: well, that makes more sense then, that it was the "if it's not, the CPU load doesn't matter" comment. However, I still stand by my _answer_. You're free to vote as you will. I would hope the edits made a while ago introducing the caveat that you should use a better way _if provided_, would sway you but, if not, we can just agree to disagree. Cheers.
paxdiablo
No probs, @jweyrich, if we all agreed, SO would be a pretty boring place :-)
paxdiablo
@paxdiablo: Guess you're the one downvoting my answer.
Frank
I prefer not to do that to "competing" answers though I have to admit I'm tempted :-) The community can decide the relative merits.
paxdiablo
Wrapping sleep in a while that way is pretty bad, if the sleep was interrupted by a signal then it should probably be respected. The user might actually wanna terminate the program - who wants to wait minutes before a program quits?
Frank
Fair enough comment. I've added a way to fix that although I don't doubt someone will be able to pick holes in the method. The important thing I was trying to raise was just that you shouldn't rely on `sleep` actually honouring your requested delay. The means to fix it are an implementation issue.
paxdiablo
@Frank, sometimes time delays are there for reasons related to real world processes. If the furnace needs 10 minutes to cool, then it might be rather important that the program wait all 10 of those minutes. Of course, I spend my days inside of embedded systems, and usually not working on desktop software, so my perspective is warped...
RBerteig
@RBerteig: I understand you, and now paxdiablo has kinda fixed his function too. But still thinks that he must mark the variable with `volatile`.
Frank
@Frank, I think `volatile sig_atomic_t finishing` is the right declaration for a variable shared between a signal handler and the main thread. I just wanted to point out that there are often outside requirements that must be respected...
RBerteig
+1  A: 

Here is how you can do it on most desktop systems:

#ifdef _WIN32
    #include <windows.h>
#else
    #include <unistd.h>
#endif

void wait( int seconds )
{   // Pretty crossplatform, both ALL POSIX compliant systems AND Windows
    #ifdef _WIN32
        Sleep( 1000 * seconds );
    #else
        sleep( seconds );
    #endif
}

int
main( int argc, char **argv)
{
    int running = 3;
    while( running )
    {   // do something
        --running;
        wait( 3 );
    }
    return 0; // OK
}

Here is how you can do it on a microcomputer / processor w/o timer:

int wait_loop0 = 10000;
int wait_loop1 = 6000;

// for microprocessor without timer, if it has a timer refer to vendor documentation and use it instead.
void
wait( int seconds )
{   // this function needs to be finetuned for the specific microprocessor
    int i, j, k;
    for(i = 0; i < seconds; i++)
    {
        for(j = 0; j < wait_loop0; j++)
        {
            for(k = 0; k < wait_loop1; k++)
            {   // waste function, volatile makes sure it is not being optimized out by compiler
                int volatile t = 120 * j * i + k;
                t = t + 5;
            }
        }
    }
}

int
main( int argc, char **argv)
{
    int running = 3;
    while( running )
    {   // do something
        --running;
        wait( 3 );
    }
    return 0; // OK
}

The waitloop variables must be fine tuned, those did work pretty close for my computer, but the frequency scale thing makes it very imprecise for a modern desktop system; So don't use there unless you're bare to the metal and not doing such stuff.

Frank
So, why the downvote?
Frank
+1 to offset an IMHO undeserved downvote. On the other hand, you are clearly assuming an OS with useful system calls and the actual question only mentions standard C which as Pax points out lacks any kind of delay call. A very large amount of C code is running on platforms without operating systems. Although some mechanism similar to `sleep()` is often a good thing to create in such platforms, it isn't required by any of the C standards.
RBerteig
I was thinking on writing of how to do it on microprocessors to without an OS, but did not quite felt to. Not really my field.
Frank
@Frank, Even with no OS, you often have a counter implemented in hardware that counts cycles of some clock. So one way is to read that counter, predict a future value, and spin in a loop until the counter reaches the value. That works for short enough waits that the counter isn't wrapping more than once while waiting. In small CPUs you sometimes have to resort to hand-tuned loops where you know exactly how many cycles are consumed per iteration. There is always a way, but it may not be pretty.
RBerteig
Precisely, it may not always be pretty. But I wounder, aren't there any microcomputers where you can set an interrupt and issue hlt to save power?
Frank
@Frank: some have it. For instance, PIC32MX has 2 types of timers. Type A has its own oscillator, while B doesn't. Both permit you to select the prescaler.
jweyrich
A: 

you can simply call delay() function. So if you want to delay the process in 3 seconds, call delay(3000)...

Owen
+1  A: 

For delays as large as one minute, sleep() is a nice choice.

If someday, you want to pause on delays smaller than one second, you may want to consider poll() with a timeout.

Both are POSIX.

mouviciel