Tuesday, August 16, 2005

CPU and Form Friendly (Long) Sleep

I've moved my blog and it's post to my new blog, please go to CPU and Form Friendly (Long) Sleep on Landman Code, Because a Sleep(1000) will seriously freeze your form for a second, the you’ll see that the solution will often be using a Application.ProcessMessages loop until the second has passed, but the problem with that loop is, it will create 100% cpu usage.

Let’s say your waiting for a response from a printer your controlling, than the 100% usage might slow down the complete process, not to mention that on a laptop you’ll be seriously eating the battery.

The following source offers a nice solution to this problem.

procedure TForm.LongDelay(DelayMs : Cardinal);
var StopTime : Cardinal;
begin
StopTime := GetTickCount + DelayMs;
while (GetTickCount < StopTime) do
begin
Application.ProcessMessages;
Sleep(1);
end;
end;

It’s pretty straight forward, offcourse when using a basic windows function, you should check out MSDN for the arguments and remarks. There was one thing that was interresting.

A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution.

This fixes one problem, you will only use the cpu when it’s idle. But that still makes this a battery eater on laptops.

I hope you liked this first post, this was just a minor subject.. But I got to start somewhere.