Program to cause 1 sec delay in C and than print stuff - c

example
sec 1 ---
sec 2 ---
sec 3 ---
Each print should have a delay of 1 sec.

In the absense of any other information in your question...
You should find a sleep function in nearly any C environment (note that it's all lower case). It's usually in time.h or unistd.h, and accepts the number of seconds that it should delay execution.
Many environments will also have nanosleep, which is an equivalent that accepts a number of nanoseconds rather than seconds. Also in time.h on many systems.
Bottom-line is that your C environment is likely to provide such a function, whether it's sleep, _sleep, Sleep, or something else similar, and whether it accepts seconds, nanoseconds, or milliseconds. You'll have to refer to the documentation for your environment to find the specific one.

#include <windows.h>
...
Sleep(timeInMilliseconds); //sleeps the current thread
hth

Unfortunately there isn't a portable version of sleep() so instead you could write a delay() function using the standard functions in time.h as follows:
void delay(int seconds)
{
time_t t = time(NULL);
while (difftime(time(NULL), t) < seconds) ;
}
Note that this isn't ideal as it keeps the cpu busy during the delay.

Related

Is it guaranteed to get 1 second using CLOCKS_PER_SEC in C?

I know clock() does not give wall-clock time, and CLOCKS_PER_SEC is system dependent value. Let's say I dont care system dependent issues, can I assume below code always waits 1 second in both GNU/Linux and Windows, because I tested it seemed ok to me. Or should I stick with system dependent sleep()/usleep() functions?
void wait_a_sec()
{
clock_t start = clock();
do
{
// wait 1 sec
/**
* Second call to clock() gives the processor time in clock ticks
* since first call to it.
* CLOCKS_PER_SEC: clock ticks per sec.
*/
} while ( clock() < (start + CLOCKS_PER_SEC) );
}
No. clock() gives you the CPU time used up by your program. Not time passed.
If for example you have one CPU and launch two instances of the program, it will wait until each has burned 1 second of active CPU time, so 2 seconds.
Also busy-waiting is generally a bad idea. Stick with sleep.

Using clock() as a timer in c

I have the following basic three lines of code to see if the clock is timing things correctly:
#include <unistd.h>
#define wait(seconds) sleep( seconds )
printf("%lu\n", clock());
wait(2);
printf("%lu\n", clock());
wait() seems to be working fine -- as when I run it, it 'feels' like it is pausing for 2s.
However, here is what the print command gives:
253778
253796
And so when I do something like:
(double) (clock() - t0) / CLOCKS_PER_SEC
It gives me useless results.
What is clock() doing here that I'm not understanding, and how can I fix this to get an accurate timer?
ISO C says that the "clock function returns the implementation's best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation."
In other words, it is not a real-time clock.
On platforms where C code runs as a process that can be put to sleep by an underlying operating system, a proper implementation of clock stops counting when that happens.
ISO C provides a function time that is intended to provide calendar time, encoded as a time_t arithmetic value. The difftime function computes the difference between two time_t values as a floating-point value of type double measuring seconds. On many systems, the precision of time_t is no better than one second, though.
There are POSIX functions for finer resolution time such as gettimeofday, or clock_gettime (with a suitable clock type argument).
If you have a read of the man page for clock(), you will see the following listed in the notes:
On several other implementations, the value returned by clock() also
includes the times of any children whose status has been collected via
wait(2) (or another wait-type call). Linux does not include the times
of waited-for children in the value returned by clock(). The times(2)
function, which explicitly returns (separate) information about the
caller and its children, may be preferable.
So clock() doesn't always include the time taken by something like wait() on all implementations. If you are on Linux, you may want to take a look at the times() function, defined in sys/times.h, as it returns a structure including the time (in clock ticks) taken by children (thus functions like wait() are included).

Creating a second-counter in C for Gameboy

So I am new to C and have been assigned the task of making a game. I'll be using a Gameboy emulator and have been discouraged from importing any libraries beyond the basics.
I would like to come up with a way to run a second-counter (that will display on screen,) but unable to use the time.h library, I feel a bit stuck.
Is there anyway I could go about doing this?
I was told that Gameboy runs rather slow, and if I could get it caught in a 'busy loop' I could 'approximate a second' and count that way.
I've considered the sleep function to do this, but that's in unistd.h library.
I've also considered perhaps setting up a loop and counting up to 10 thousand (or whatever number may take a second to calculate,) but all of this will be happening simultaneously to the game at hand, and I am afraid things like that will delay the gameplay and other things happening.
Any recommendations?
Edit: I think anything beyond stdlib.h and stdio.h is disallowed.
The gameboy has a hardware timer.
Sometimes it's useful to have a timer that interrupts
at regular intervals for routines that require
periodic or percise updates. The timer in the GameBoy
has a selectable frequency of 4096, 16384, 65536, or
262144 Hertz. This frequency increments the Timer
Counter (TIMA). When it overflows, it generates an
interrupt. It is then loaded with the contents of
Timer Modulo (TMA). The following are examples:
;This interval timer interrupts 4096 times per second
ld a,-1
ld ($FF06),a ;Set TMA to divide clock by 1
ld a,4
ld ($FF07),a ;Set clock to 4096 Hertz
So write your interrupt handler to keep track of the number of interrupts and update the displayed clock every 4096 (=0x1000) interrupts.
Implementations of some (not all) delay functions are blocking, (nothing else in code runs until delay function returns. Also are susceptible to run-time options such as whether in debug or release mode of execution, etc. (i.e. will run at inconsistent times depending on these modes)
an implementation that is not blocking, i.e. that during the delay, system events are given time-slices to continue would likely require use of multi-threading. But since C is not intrinsically a multithreaded language, you would have to use additional non-standard C libs that you are not allowed to use.
Given you understand this, and would be OK with a simple technique (i.e. blocking, with susceptibility to execution mode), then just use a simple time loop. Follow these steps:
1) create a development (test) function that is simply a for loop with a hard-coded index value:
void sec_delay(void)
{
//loop incrementer value
int i = 334000000;//change value here during testing to adjust duration of calling
//test program. eg: for 60 calls, should elapse 60 seconds.
//this value run on PC shown below provided 1 second duration.
while(i-- > 0);
}
2) characterize sec_delay
Run a program that calls sec delay 60 times and time its execution against a clock or stopwatch.
void sec_delay(void);
int main(void)
{
int i;
for(i=0;i<60;i++)//target 60 seconds, change to 600 for 10 min. or 10 for 10 sec.
{
sec_delay();
}
printf("Done");//uses stdio.h
getchar(); //uses stdio.h
return 0;
}
3) Use the execution time for this executable to adjust the loop incrementer value so you can be as close to 1 minute as possible. For higher accuracy, loop the main program 600 times and map the incrementer in sec_loop so that time elapsed is 10 minutes.
Once you have characterized the sec_delay() function as described, you essentially have something you can use for a 1 second timer.
4) Now that you have a a value for 1 second elaplse time, create a new prototype:
void delay(float);
And create a #define:
#define SEC 334000000.0 //enter your value here in float
Finally, define delay() function:
void delay(float secs)//note, fractions of seconds can be called
{
if(secs < 0) break;//leave for negative values;
int i = (int)secs*SEC ;
while(i-- > 0);
}

Is Sleep() inaccurate?

I'm working on a timing system and I'll implement a timer class.
#include <windows.h>
#include <stdio.h>
#include <time.h>
int main()
{
clock_t t1, t2;
t1 = clock();
Sleep(10);
t2 = clock();
printf("%i\n", (int)(t2 - t1));
return 0;
}
This program should print "10" but it prints "15" or "16". I need more accurate which is less than 1 ms! Suggestions? (maybe with select()'s timeout?)
NOTE: I've run this program on Windows 7 Ultimate x86. Program compiled with MinGW (C/C++) x86.
NOW I THINK >>
Sleep() is accurate to the operating system's clock interrupt rate. Which by default on Windows ticks 64 times per second. Or once every 15.625 msec, as you found out.
You can increase that rate, call timeBeginPeriod(10). Use timeEndPeriod(10) when you're done. You are still subject to normal thread scheduling latencies so you still don't have a guarantee that your thread will resume running after 10 msec. And won't when the machine is heavily loaded. Using SetThreadPriority() to boost the priority, increasing the odds that it will.
Your problem is that the "clock" only ticks 64 times per second (I've seen systems that can go up to 2000, but no higher). If you are creating a timer class, you probably want to have much higher resolution than even 2000. Use QueryPerformanceCounter to get higher resolution. See QueryPerformanceCounter and overflows for an example.
Note that if you want to sleep for very short intervals, you will have to call QueryPerformanceCounter in a tight loop.
Sleep() is not accurate in the way you want it to be.
It will cause the thread to sleep for AT LEAST the length of time you specify, but there's no guarantee that the OS will return control to your thread at exactly that specified time.

wait for specifed time without using while C

I'm wondering how to make a time delay of a few seconds using C , without using while loop. The samples I got are using while loop.
This works but I dont want to use the while loop. Please help
while(clock() < endwaitTime)
{
if(!GetFlag())
{
print(" Canceled ");
return ;
}
}
You can use sleep() to pause your application for the given amount of seconds, or you can use usleep() to pause your application for the given amount of microseconds.
You can also explore the blocking properties of select() to have a microsecond precision pausing. Some applications prefer to do that, don't ask me why.
About your while() loop, never do that. It is not pausing. Your application will loop using 99% of the CPU until the time has elapsed. Its a very dumb way of doing that.
Also, its preferable that you use time() to get the current UNIX time and use that as reference, and difftime() to get the time delta in seconds to use with sleep().
You may have problems with clock(), because this function on a 32-bit system will return the same number every ~72 minutes, and you will often have a endwaitTime with lower value than the current return value of clock().
Following http://linux.die.net/man/3/sleep
#include <unistd.h>
...
// note clock() is seconds of CPU time, but we will sleep and not use CPU time
// therefore clock() is not useful here ---
// Instead expiration should be tested with time(), which gives the "date/time" in secs
// since Jan 1, 1970
long int expiration = time()+300 ; // 5 minutes = 300 secs. Change this as needed.
while(time() < expiration)
{
sleep(2); // dont chew up CPU time, but check every 2 seconds
if(!GetFlag())
{
print(" Canceled ");
return ;
}
}
...
Of course, you can get rid of the while loop completely if a single sleep() is good enough. For a short pause this may be OK. Input is still queued by Linux while the process is sleeping, and will be delivered to the stdin of the program when it wakes up from the sleep.

Resources