I found that if I put "sleep(1);" in thread.Execute's while-loop, the CPU usage of the application is nearly 0%, but when I put "yield;" instead, the CPU usage if about 25%.
Yep, but your
Sleep(1) does not freeze the program for
1ms, and for much longer. It probably stops the program for about
16ms. The clock's resolution is not so high, so if you need to increase it, use the
TimeBeginPeriod and
TimeEndPeriod functions from the
MMSystem unit.
But even if you call
TimeBeginPeriod(1), the
Sleep(1) will pause the program for
2ms — this procedure is not very precise for such small values.
If you want to know what is the possible timer lowest period, use
TimeGetDevCaps and use the value from the
wPeriodMin field in the
TimeBeginPeriod call. Example below:
uses
MMSystem;
// field to store the period
FTimerPeriod: Integer;
// somewhere at the beginning of the program code
var
Periods: TTimeCaps;
begin
if TimeGetDevCaps(@Periods, SizeOf(Periods)) = TIMERR_NOERROR then
begin
FTimerPeriod := Periods.wPeriodMin;
TimeBeginPeriod(FTimerPeriod);
end
else
FTimerPeriod := -1;
end;
// somewhere at the end of the program code
begin
if FTimerPeriod <> -1 then
TimeEndPeriod(FTimerPeriod);
end;
I'm using such code in my platformer — changing system timer period is mandatory, works excellent.
BTW, I have tested that sleep(0) is similar to yield.
Sleep(0) does nothing, does not stop the program, so the processor's power consumption will still be full. The smallest actually working value for
Sleep procedure is
1, and the real shortest break is that lasting
2ms.