转贴stanleyxu在QQ群里头的思路。
stanleyxu(*)(38656530) 09:07:29
其实就是创建线程
双核就创建2个
然后呢,我规定,比如100毫秒内,20毫秒是sleep,80毫秒是processmessage
这样cpu占用大致保持在80
先通过这个思路实现一个线程,控制cpu占用,cpu值是个属性
然后你就可以写个什么sin函数,控制曲线,包括振幅,速度
program Project1;
{$APPTYPE CONSOLE}
uses
Classes, SysUtils, Windows;
procedure ProcessMessages;
var
MsgRec : TMsg;
begin
while PeekMessage(MsgRec, 0 {FWindowHandle}, 0, 0, PM_REMOVE) do begin
TranslateMessage(MsgRec);
DispatchMessage(MsgRec)
end;
end;
procedure Delay(MilliSecs: DWORD);
var
T: DWORD;
begin
T := GetTickCount;
while GetTickCount - T < MilliSecs do
begin
// Any more precisely way?
ProcessMessages;
end;
end;
function GetNumberOfProcessors: Integer;
var
SI: TSystemInfo;
begin
GetSystemInfo(SI);
Result := SI.dwNumberOfProcessors;
end;
type
TCPUConsumerThread = class(TThread)
public
nRound: Extended;
ExpectedCPUusage: Integer;
function GetSleepDuration: DWORD;
procedure Execute; override;
end;
const
DelayDuration = 56;
TaskManRefreshRate = 100; //not less than 56 ms
var
Working: Boolean;
function TCPUConsumerThread.GetSleepDuration: DWORD;
const
Delta = Pi / 80;
begin
ExpectedCPUusage := Round((Sin(nRound / 4) + 2){1-3} * 10);
nRound := nRound + Delta;
Result := TaskManRefreshRate * (100 - ExpectedCPUusage) div 100;
end;
procedure TCPUConsumerThread.Execute;
var
SleepDurationOfThisRound: DWORD;
I: Integer;
begin
while Working do
begin
SleepDurationOfThisRound := GetSleepDuration;
if TaskManRefreshRate > SleepDurationOfThisRound then
Delay(TaskManRefreshRate - SleepDurationOfThisRound);
if SleepDurationOfThisRound > 0 then
Sleep(SleepDurationOfThisRound);
end;
end;
var
ACPUConsumerThread: TCPUConsumerThread;
I: Integer;
begin
Working := True;
for I := 1 to GetNumberOfProcessors do
with TCPUConsumerThread.Create(True) do
begin
FreeOnTerminate := True;
ExpectedCPUusage := 20;
Resume;
end;
WriteLn('Running... (press any key to abort)');
ReadLn;
Working := False;
WriteLn('press any key to exit');
ReadLn;
end.
stanleyxu(*)(38656530) 09:10:53
我的思路大致这样,现在振幅不高兴仔细研究了。谁有兴趣谁去继续研究
要让cpu占用到100,我用delay函数,具体实现还可以改,可能可以直接用什么cpu指令,强制占用cpu之类的?
因为delay里面用到GetTickCount,而这个函数的精度最低就是56毫秒,所以我硬性规定,每次占用cpu至少56毫秒。
因为时间再短,可能就误差很厉害了。
|