How to make Delay in C or C++

Did you ever want to make a C program wait for a certain time?

You can set up a technique to allow time to tick away, for example: when showing a splash page (a notice or hint) for a game.





Okay, here are some ways to make the program "stand still", Make your CPU work for some time without producing any noticeable event.Do no other operation during that delay, in order to create a simple time-delay.

The "for-loop" technique

  1. 1
    Use a typical "for" loop followed by a null statement to implement time delay.

  2. 2
    Write as follows, for an example:
    • for (i=1 ; i<100 ; i++) ;

    • The statement followed by the ";" makes the computer execute the loop 100 times without any noticeable event. It just creates a time delay.


The "sleep()" Technique

  1. 1
    Use sleep() The function called sleep(int ms) declared in <time.h> which makes the program wait for the time in milliseconds specified.

  2. 2
    Include the following line in your program before "int main()":
    • #include <time.h>


  3. 3
    Insert, wherever you need your program to make a delay:
    • sleep(1000);

    • Change the "1000" to the number of milliseconds you want to wait (for example, if you want to make a 2 second delay, replace it with "2000".







SAMPLE CODE :

A program that waits a given amount of seconds:
#include <stdio.h>

#include <time.h>



int main()

{

int del; // The delay period

printf("Enter the delay time (in seconds): ");

scanf("%i",&del);

del *= 1000; // Multiply it by 1000 to convert to milliseconds

Delay(del); // Delay.

printf("Done.");

return 0;

}



A program that counts down from 10 to 0:
#include <stdio.h>

#include <time.h>



int main()

{

int i;

for(i = 10; i >= 0; i--)

{

printf("%i\n",i); // Write the current 'countdown' number

Delay(1000); // Wait a second

}

return 0;

}




Tips:

  • The above logic can be implemented by using any looping structure followed by a null statement-";",like by using while or do-while loops.

  • A millisecond is 1/1000 of a second.

Warning :


  • Note that when using the for-loop technique, you might need a very big span for i, because an empty statement is executed very fast. Such big numbers may not fit in an integer type.

  • If you are using the for-loop, the compiler may optimize the code, and, because the loop does nothing, remove it. This doesn't happen when using Delay().

  • This technique is generally useless in anything besides a trivial program. In general, use timers or an event-driven approach to implement this. Otherwise the program will become unresponsive during the delay time, and that's not always a good thing. Besides, choosing N in your loop, if it depends on instruction execution, may have surprising results. Apparently the original author has never heard of an optimizing compiler...it may optimize away the entire loop if it actually does nothing !

0 Comments
Disqus
Fb Comments
Comments :

0 comments:

Post a Comment