Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Precise Timer in C 1

Status
Not open for further replies.

Bannon

Programmer
Jun 10, 2001
23
US
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?

thnx
Bannon
 
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.

while(clock()-start < delay)
;
printf(&quot;Done&quot;);
}


hope it works.

Regards,
SwapSawe.
 
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:

#include <unistd.h>
#include <signal.h>
#include <stdio.h>

/* ... */

static volatile sig_atomic_t woken_up;

void handler(int sig)
{
woken_up=1;
}

int main(void)
{
signal(SIGALRM,handler);
woken_up=1;

for (;;) {
if (woken_up) {
puts(&quot;doing other processing&quot;);
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.

Russ
bobbitts@hotmail.com
 
Thanx Russ,

for pointing out that error, I don't know how I did that mistake.

Thanx again.

SwapSawe
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top