Thread: Create a delay without using Sleep

  1. #1
    Registered User Bag a Bones's Avatar
    Join Date
    Dec 2005
    Posts
    15

    Create a delay without using Sleep

    Its almost exam time and my teacher would like us to learn how to create a delay in our programs without using the Sleep function in the windows.h library. He said that we might do somthing like create a loop where there is a counter that will count to a very high number or somthing like that. I tried somthing like this:
    Code:
    while (1)
    {
      a++;
      if (a < 10000)
      {
           //code
      }
      elseif (a >100000)
      {
          //more code
      }
      else
      {
         //some other code
      }
    }
    There seemed to be no diference between the two. Any suggestions? Thanks

    BTW: My teacher said that sleep isn't a good function in most cases because it makes the system inactive for that time and no input will do anything, a function that can still retrieve input while pausing would be helpfull aswell.

    Exam in 2 days!
    Current project - Mouse Odometer

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Running a loop isn't a good idea either because it takes CPU cycles.

    If you are not getting any differences, maybe make your loops longer (or nest them, or use a double and increment by 0.001 or something small). The reason is that the computer is very fast, and 100000 runs through a simple loop is very quick.

  3. #3
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    Busy loops are a poor way of creating delays; they tie up CPU resources (in a multi-programming environment), and depend on the speed of the CPU. The counter-loop based delay ties up your program until it exits, and uses a lot of CPU cycles that could be used for other processes.

    There are standard ways to create somewhat predictable delays.

    With Windows (when using an event loop), you set up a timer event and then wait until you get the timer event before proceeding with your current code (though you should process all of the events that occur; they should not relate to the part of the program you want the delay in). This, of course, only works with one OS (though the same concept is applicable in many graphical environments.)

    For POSIX environments, and for console apps, another method is to use the alarm(2) system call and set up a signal handler for the event (SIGALRM) that's triggered when the alarm fires off.

    The standard POSIX library call sleep(3) does not block the OS from doing other things, just the process that calls it. This may not match the Windows sleep function you mentioned in your posting.

    It's been about 6 years since I did any serious programming on Windows, so my resources and memory on that environment are a bit scarce at the moment.
    Insert obnoxious but pithy remark here

  4. #4
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    if you are going to go by way of the loop, empty loops will iterate remarkably fast even if the value is large. the argument would be that this is a very CPU intensive delay, but if you want to have a loop based delay that doesnt require 100 million iterations, try a loop that prints white space to the console every iteration - really slows it down.

    Code:
    int i;
    
    for (i=0; i<100000; i++)
    {
           printf (" ");
    }
    i have a 3Ghz processor and that code ran for about 3 seconds - can easily be increased by increasing the number of iterations. also, cout is marginally slower than printf - something i saw in the faq once.

    there is yet another method which i have used, and it allows you to specify in seconds roughly how long you want to delay - you will need time.h.

    Code:
        printf ("Enter how long: ");
        scanf ("%d", &len);
        current = time(0);
        stop = current + len;
        printf ("%d, %d\n\n", current, stop);
        while (1)
        {
              current = time (0);
              if (current >= stop)
                 break;
        }
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  5. #5
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by Bag a Bones
    Its almost exam time and my teacher would like us to learn how to create a delay in our programs without using the Sleep function in the windows.h library. He said that we might do somthing like create a loop where there is a counter that will count to a very high number or somthing like that.
    BTW: My teacher said that sleep isn't a good function in most cases because it makes the system inactive for that time and no input will do anything, a function that can still retrieve input while pausing would be helpfull aswell.
    your teacher sounds like an idiot. Sleep does not "make the system inactive", it yields your program to the kernel for a specified length of time (on most windows platforms, it's at least 10-15ms to allow for a thread switch).

    As for using an empty loop as a delay, any decent compiler will optimise it out of the program.
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  6. #6
    Cat Lover
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109
    Quote Originally Posted by Richie T
    if you are going to go by way of the loop, empty loops will iterate remarkably fast even if the value is large. the argument would be that this is a very CPU intensive delay, but if you want to have a loop based delay that doesnt require 100 million iterations, try a loop that prints white space to the console every iteration - really slows it down.

    Code:
    int i;
    
    for (i=0; i<100000; i++)
    {
           printf (" ");
    }
    i have a 3Ghz processor and that code ran for about 3 seconds - can easily be increased by increasing the number of iterations. also, cout is marginally slower than printf - something i saw in the faq once.
    Although something I've noticed when having great big chunks of output statements (using cout), the output lags behind the actual execution, so while the output is still at the x repeat, the actual program is up to 2x or whatever.

    That was using the gcc compiler that came with my powerbook, osx 10.2.8, so maybe my computer's just screwed up.


    I think what he meant by this
    My teacher said that sleep isn't a good function in most cases because it makes the system inactive for that time and no input will do anything, a function that can still retrieve input while pausing would be helpfull aswell.
    Is that the program won't process input during that time, so he wants something that'll pause the program before executing an event, but will still take input and execute other program commands.

    Possibly he meant something like
    Code:
    while(time<time_to_go_to)
    {
      check_for_input;
      if(input) Do_Input_Command;
    }
    Do_Command_After_Delay

  7. #7
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    one way to create a delay without using Sleep() is to use current time -- but like other posts to this thread, it will consume too much cpu time to be useful
    Code:
    int delay(long seconds)
    {
       time_t t1;
       t1 = time(0) + seconds;
      while(  time(0) < t1)
         ;
    }

  8. #8
    Registered User
    Join Date
    May 2005
    Posts
    2

    Use No Op.

    Look into to using the Assemble command 'NOP'

    You Should be abile to put in line ASM code in your C++ App.


    _asm

    NOP
    NOP
    ;//probly a loop to get a set delay length;

    _endasm;

  9. #9
    Registered User
    Join Date
    Aug 2002
    Location
    Hermosa Beach, CA
    Posts
    446
    You could also use the windows function WaitForSingleObjectEx. It puts the current thread to sleep much like sleep does, except that if the handle given to it was created as an event (with CreateEvent()), the sleep can be woken up by signaling the event from another thread (using SetEvent()).
    The crows maintain that a single crow could destroy the heavens. Doubtless this is so. But it proves nothing against the heavens, for the heavens signify simply: the impossibility of crows.

  10. #10
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    Quote Originally Posted by GletchM
    Look into to using the Assemble command 'NOP'

    You Should be abile to put in line ASM code in your C++ App.


    _asm

    NOP
    NOP
    ;//probly a loop to get a set delay length;

    _endasm;
    you'd have to use trillions of them to sleep for 1 second!

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Look into to using the Assemble command 'NOP'

    You Should be abile to put in line ASM code in your C++ App.


    _asm

    NOP
    NOP
    ;//probly a loop to get a set delay length;

    _endasm;
    And most compilers around here don't support assembler anyway (Dev-C++ and MSVC).

    See the FAQ: http://faq.cprogramming.com/cgi-bin/...&id=1043284392
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  12. #12
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    Dev-C++ supported inline assembly when I stopped using it, and I know MSVC++ does as well, just not with that sytanx. For VS 2003:
    Code:
    _asm
    {
    
    }
    On Dev-C++ I remember it used AT&T syntax unless you set a compiler switch, though it had some issues if you tried to use intel syntax if I recall correctly. Come to think of it, pretty much everything about using inline asm in Dev was a pain, especially the me-not-knowing-assembly part
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  13. #13
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    You should be using a timer for something like this. Using busy loops like your teacher suggested is just retarded. For Windows, look into SetTimer(), or CreateTimerQueueTimer().

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Button handler
    By Nephiroth in forum Windows Programming
    Replies: 8
    Last Post: 03-12-2006, 06:23 AM
  2. How to create a file association program?
    By eShain in forum Windows Programming
    Replies: 1
    Last Post: 03-06-2006, 12:15 PM
  3. Adding delay to all packets (incoming and leaving)
    By ingtabby in forum Windows Programming
    Replies: 1
    Last Post: 01-31-2006, 10:33 AM
  4. Cannot create MDI Client Win
    By JaWiB in forum Windows Programming
    Replies: 1
    Last Post: 10-31-2005, 10:05 PM
  5. Delay
    By CanadianOutlaw in forum C++ Programming
    Replies: 4
    Last Post: 09-13-2001, 06:28 AM