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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Alternative to Sleep-Function

Status
Not open for further replies.

zigular

Technical User
Jun 29, 2004
18
0
0
DE
hello,
anybody knows a better methode than Sleep() to force the processor to a hold-on? The difference between Sleep(1) and //Sleep(1) is enourmouos, but between Sleep(1) and Sleep (2) or higher not so much. I think Sleep is not really the best/exact way tot do.

cheers
hilmar

ps: by the way, i try some things this night, so it would be great also to answer to my home address: hilmar.franz@web.de

thank you!!
 
Sleep doesn't force the processor to anything. It simply halts your application.

> I think Sleep is not really the best/exact way tot do

Well, Windows isn't a real-time OS. Don't expect too much precision from its API.

You could however make aloop yourself that whecks CPU ticks for some time.

See doc on QueryPerformanceCounter and QueryPerformanceFrequency

/Per
[sub]
"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."[/sub]
 
You can do it like this, but your program will use a lot more CPU this way:

timeBeginPeriod(1); // use 1 ms precision

DWORD dwStop = timeGetTime() + 1;
while(timeGetTime() != dwStop);

// It will have waited 1 millisecond here

The only problem with this is that it may end up waiting less, because it could have been close to the end of a millisecond when you got dwStop.
 
If You really wish to hold processor for exactly 1 ms, You can make it from a driver only, that hooks int0 (from system timer). So you can add to Windows real time task.
 
i dont know,but i think that this also might work:

Code:
#include <ctime>
.....
...
void sleep( clock_t wait ) 
{
   clock_t goal;
   goal = wait + clock();
   while( goal > clock() )
      ;
}
 
The reason why the difference between //Sleep(1) and Sleep(1) is enormous, but not so much for Sleep(1) and Sleep(2), is because there is no difference between Sleep(1) and Sleep(2). It will end up rounding up the value to the nearest multiple of the operating system's scheduling granularity, which I think is either 5ms or 10ms (could be wrong).

The two other solutions for "sleeping" given here are not actually doing a sleep at all. They are doing what's called a "busy wait". Instead of putting the process to sleep so that other processes can run instead, it consumes all the CPU and wastes it polling the clock. This might be okay for your program, but it will make everything else running on the same CPU a lot slower unless you muck with the process priority.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top