How can I make a precise time in C? I'm used to VB. Its easy there But thats why Its slow. I was thinking a loop, but wont that vary depending on a machine and its load?
If I could depict your question correctly, u want to know how to make the system wait for a specific time.
There are various ways one of them is using library functions for eg. delay(long milliseconds).
However these are not portable.
Try this code if required >
# include <clock.h> // describes clock() and clock_t type.
# include <stdio.h>
clock_t start,delay;
float secs;
//Accept the no. of seconds to wait in variable secs.
delay=secs*CLOCKS_PER_SEC; // Converting in to clock ticks.
start = clock(); // will assign system time to start.
Actually, the clock() function is a portable function, but <clock.h> is not a standard header. Rather, the clock() function is found in <time.h>.
Also, clock() returns the *processor time used*(not the system time). So, Swap's example is portable (minus the non-standard header <clock.h>).
The caveat is that it is very processor intensive and probably won't give the accuracy that you'll want. Typically an implementation will provide its own extensions for accomplishing what you want.
POSIX provides a sleep() that sleeps for the number of seconds in its argument:
#include <unistd.h>
/* ... */
sleep(5); /* Process is put to sleep for 5 seconds */
POSIX also provides alarm() and signal() if you're looking for a solution where the process does other processing and periodically does something else:
int main(void)
{
signal(SIGALRM,handler);
woken_up=1;
for (; {
if (woken_up) {
puts("doing other processing"
alarm(5); /* A SIGALRM will be sent to the process in 5 seconds */
woken_up=0;
}
/* Do other processing */
}
return 0;
}
If you need more precise resolution, there's a BSD function called usleep() that your system might provide which sleeps for N microseconds.
Of course, most of the above will probably not be offered by DOS/Win32 implementations, but I'm sure you'll find comparable functions with different names.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.