How to sleep accurately

Daniel Giddings danielg at microforte.com
Wed Jun 27 19:01:49 PDT 2007


I'm not sure of the best way to do it but I'm interested in what people 
think ;-)

You can use gettimeofday under linux instead of clock. It's in 
std.c.linux.linux.

long getTime() // in ms
{
	timeval t;
	struct_timezone z;

	gettimeofday(&t, &z);

	return t.tv_sec * 1000 + t.tv_usec / 1000;
}


Jason House wrote:
> I've been trying for a while now to get a sleep routine that actually 
> works as I expect it to (sleeping for the time specified within a 
> practical error margin).
> 
> 
> Let's say you want to sleep for 0.1 seconds (wall clock).
> 
> msleep(100); // Not available under linux
> 
> usleep(100000); // Not guaranteed to be reentrant...
> 
> timespec ts;
> ts.sec = 0;
> ts.nsec = 100000000;
> nanosleep(ts,cast(timespec)null); // Thread safe
> 
> 
> Unfortunately, all of those can be interrupted by signals (such as the 
> garbage collector running).  Ignoring the reentrant issue (which seems 
> to not affect stuff in practice), I tried the following:
> 
> time_t now = clock();
> time_t stop = now + 100000/CLOCKS_PER_SECOND;
> while(now<stop){
>   usleep(stop-now);
>   now = clock();
> }
> 
> 
> On windows, that seemed to work.  Under linux, clock() keeps returning 
> zero!  It appears that it returns the process time that elapsed since 
> the last call to clock rather than using any kind of absolute reference 
> and is useless.
> 
> Does anyone have a good way of doing this?


More information about the Digitalmars-d-learn mailing list