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.
Related
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.
I have the following code:
#include <stdio.h>
#include <time.h>
int main(){
clock_t timerS;
int i=1, targetTime=2;
scanf("%d", &targetTime);
while(i!=0){
timerS = clock();
while ((double)((clock() - timerS) / CLOCKS_PER_SEC) < targetTime){
//do something
}
//do another thing but delayed by the given time
if(targetTime>=0.5)
targetTime-=0.02;
else i=0;
}
return 0;
}
And what I want to do is having a loop which does something for (initially) an inputted amount of seconds and also doing another thing after targetTime-seconds have passed.
But after the first loop, to change the speed with which these operations are made(more specifically -0.02 seconds in this case).
An example would be getting multiple user inputs from user for 2 seconds, and displaying all the inputs made in these 2 seconds afterwards.
First problem is
If the initial given time is smaller than 1 second (for example 0.6), the other thing isn't delayed by 0.6 seconds, but is done immediately.
Second problem is
Actually similar to the first, if I subtract 0.02 seconds (in this case) from targetTime, it again does the other thing immediately and not in targetTime-0.02 seconds as I intend it to.
I'm new to this "clock" and "time" topic in C so I guess I'm doing something wrong regarding how these operations should be done. Also, please don't give an overly-complicated explanation/solution because of the above-mentioned reason.
Thanks!
Don't use the clock(2) system call, as it is obsolete and has been fully superseeded by machine independent replacements.
You can use, if your system supports it, clock_gettime(2), that will give you up to nanosecond precission (depending on the platform, but at least in linux on Intel architectures it is almost warranted) or, if you cannot use it, at least you'll have gettimeofday(2), which is derived from BSD systems, and provides you with a clock with microsecond resolution.
If you want to stop your program for some delay, you have also sleep(2) (second based) usleep(2) (microsecond based) or even nsleep(2) (nanosecond based)
Anyway, any of these calls has a tick that is not based on the system heartbeat, and the resolution is uniform and not system dependant.
I mistakenly initiated targetTime as int instead of double. Changing it to double solves the issue easily. Sorry!
I am making an emulator for the 6502 CPU and i want to control the frequency at which it is running.
Without any delay, my max average frequency is about 70-80 MHz. However, when i try to use nanosleep in order to control frequency, it only works until i reach 1 mS delay (1000000 nS).
If i try to set the delay any lower, for example to .1 mS, it does not change the average execution timing. What is strange to me is that if i set the delay to .1 mS, the actual delay turns out to be ~.008 mS and it does not change for any value in range 1-99999 nS.
I have tried compiling the code both in debug and release mode
Am i using nanosleep wrong? It is my first time using nanosleep, i have only used sleep and usleep before, so i am a bit confused.
Is there any better way to control the frequency of code execution?
How to correctly use nanosleep() to run code at specific frequency?
I say it's impossible to use nanosleep to run code at specific frequency (or, it's possible, up to a certain accuracy with some drift?). From man nanosleep emphasis mine, but whole is relevant:
The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified
by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching
function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up
to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the
case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the
system clock CLOCK_REALTIME.
Is there any better way to control the frequency of code execution?
Use timers and try to depend on the kernel to properly schedule periodic execution, rather then doing it yourself. Use timer_create to request an interrupt after specified timeout and run your code after that timeout, and you may also consider making your process a real-time process. In pseudocode I think I would:
void timer_thread(union sigval s) {
do_your_code();
}
int main() {
timer_t t;
timer_create(CLOCK_MONOTONIC, &(struct sigevent){
.sigev_notify = SIGEV_THREAD,
.sigev_notify_function = timer_thread
}, &t);
timer_settime(t, &(struct itimerspec){{.tv_sec = 1},{.tv_sec = 1}}, 0);
while (1) {
// just do nothing - code will be triggered in separate thread by timer
pause();
}
}
I've been wanting a pause function for a while and I found this. Being a beginner in C, I can't be for sure but it looks like functions from <clock.h>.
I would like to implement this into my code, but not without understanding it.
void wait(int seconds){
clock_t start, end;
start = clock();
end = clock();
while (((end-start) / CLOCKS_PER_SEC) = !seconds)
end = clock();
}
It's just a busy-wait loop, which is a very nasty way of implementing a delay, because it pegs the CPU at 100% while doing nothing. Use sleep() instead:
#include <unistd.h>
void wait(int seconds)
{
sleep(seconds);
}
Also note that the code given in the question is buggy:
while (((end-start) / CLOCKS_PER_SEC) = !seconds)
should be:
while (((end-start) / CLOCKS_PER_SEC) != seconds)
or better still:
while (((end-start) / CLOCKS_PER_SEC) < seconds)
(but as mentioned above, you shouldn't even be using this code anyway).
Generally, clock_t is a structure in library. It returns the number of clock ticks elapsed from the program initiation till end or till you want to count the time.
If you want to know more you can read details here: http://www.tutorialspoint.com/c_standard_library/c_function_clock.htm
The clock() function returns the number of system clock cycles that have occurred since the program began execution.
Here is the prototype: clock_t clock(void);
Note that, the return value is not in seconds. To convert the result into seconds, you have to divide the return value by CLOCKS_PER_SEC macro.
You program just does this. Functionally it stops the program execution for seconds seconds (you pass this value as an argument to the wait function).
By the way, it uses time.h, not clock.h. And it is not the right point to start learning C.
To learn more: http://www.cplusplus.com/reference/ctime/?kw=time.h
clock function in <ctime>:
Returns the processor time consumed by the program.
The value returned is expressed in clock ticks, which are units of
time of a constant but system-specific length (with a relation of
CLOCKS_PER_SEC clock ticks per second).
reference
So, basically it returns number of processor ticks passed since the start of the program. While the processor tick is the number of processor instructions executed by a process, it does not account for IO time and any such that does not use CPU.
CLOCKS_PER_SEC Is the average number of CPU ticks executed by machine and varies from machine to machine, even it (probably) changes time to time, because doing too much IO will cause overall decrease for each process CLOCKS_PER_SEC because more time will be spent not using CPU.
Also this statement: (end-start) / CLOCKS_PER_SEC) = !seconds
is not correct, because the right implementation is
while (((end-start) / CLOCKS_PER_SEC) != seconds)
end = clock();
Does the trick of busy waiting, program will be trapped inside this while loop until seconds seconds will be passed using CPU clocks and CLOCKS_PER_SEC to determine time passed.
Although I would suggest changing it to:
while (((end-start) / CLOCKS_PER_SEC) < seconds)
end = clock();
Because if process has low priority, or computer is too busy handling many processes chance is one CPU tick can take more than one second (probably when system is crashed, for some buggy program who take up a lot of resources and has high enough priority to cause CPU starvation).
Finally, I do not recommend using it, because you are still using CPU while waiting which can be avoided by using sleep tools discussed here
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.