03
Jul 08

Delphi: Utils :: WorkOnProcessor

:: articles :: by Gilberto Saraiva

Folks,

For evebody who wants to control how the application’s threads and processes will consume the CPU I wrote this function to provide an easy way to do this.

 Delphi |  copy code |? 
01
uses Windows;
02
 
03
type
04
  TWorkOnProcessorUseMode = (cpuNum, cpuPerc, cpuIndex);
05
 
06
procedure WorkOnProcessor(AUse: Cardinal; AMode: TWorkOnProcessorUseMode);
07
var
08
  Mask: integer;
09
  lpSystemInfo: TSystemInfo;
10
 
11
  function ToMask(m: integer): integer;
12
  var
13
    i: integer;
14
  begin
15
    Result := 0;
16
    for i := 0 to m - 1 do
17
      Result := Result + (1 shl i);
18
  end;
19
begin
20
  GetSystemInfo(lpSystemInfo);
21
  with lpSystemInfo do
22
  begin
23
    case AMode of
24
      cpuNum: begin
25
        if AUse > dwNumberOfProcessors then
26
          AUse := dwNumberOfProcessors;
27
      end;
28
      cpuPerc: begin
29
        if AUse > 100 then AUse := 100;
30
        AUse := Round(dwNumberOfProcessors / 100 * AUse);
31
      end;
32
    end;
33
    if AMode <> cpuIndex then
34
    begin
35
      Mask := ToMask(dwNumberOfProcessors);
36
      Mask := Mask xor ToMask(dwNumberOfProcessors - AUse);
37
    end else
38
      Mask := (1 shl (AUse - 1));
39
    SetProcessAffinityMask(GetCurrentProcess, Mask);
40
  end;    
41
end;

You’ll have three ways to put your application running only on the processor(s) you want.

  • cpuNum mode:
    With this mode you’ll be able to specify the number of processors you want to use. The logical structure will count from the first processor.

  • cpuPerc mode:
    With this mode you’ll be able to specify a percentage to use of all processors on the machine. If the machine have four processors and you specify 50 (50%) on the first param, your application will use 2 cores. If 2 cores and 50% will use 1 core.

  • cpuIndex mode:
    With this mode you’ll be able to specify the processor you want to use. If you have 4 cores and you want to use only the third core, specify 3 on the first param and your application will use only the 3º core and no one more.
  • A little detail:
    Your application starts without a setting about what processor will be used and all threads and processes created before the use of the function above can be not modified and so the process can keep on an unspecified core.
    The best way to use this function is declaring it on the DPR and using it before Application.Initialize;
    Ex:

     Delphi |  copy code |? 
    1
    // on the .DPR of the project
    2
    begin
    3
      WorkOnProcessor(50, cpuPerc);
    4
      Application.Initialize;
    5
      Application.CreateForm(TForm1, Form1);
    6
      Application.Run;
    7
    end.

    Tags: , , ,


    Leave a comment