Skip to content

Instantly share code, notes, and snippets.

@zedxxx zedxxx/FastDigitCount.dpr
Last active Jul 13, 2019

Embed
What would you like to do?
program FastDigitCount;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Diagnostics;
function Digits_1(const S: string): Integer;
var
C: Char;
begin
Result := 0;
for C := '0' to '9' do begin
Inc(Result, S.CountChar(C));
end;
end;
function Digits_2(const S: string): Integer;
var
I: Integer;
begin
Result := 0;
for I := 1 to Length(S) do begin
if CharInSet(S[I], ['0'..'9']) then begin
Inc(Result);
end;
end;
end;
function DigitCount(const AStr: string): Integer;
var
P: PChar;
begin
Result := 0;
P := PChar(AStr);
while P^ <> #0 do begin
if (P^ >= '0') and (P^ <= '9') then begin
Inc(Result);
end;
Inc(P);
end;
end;
procedure DoTest;
const
cTestCount = 1000000;
var
I, J: Integer;
VStr: string;
VStopwatch: TStopwatch;
begin
VStr := 'fgh0hj2jjj544j66445hhhhhhhhggggggggjjjjjjjjjjjjyyyyyyyy666548422rrg';
J := 0;
VStopwatch := TStopwatch.StartNew;
for I := 0 to cTestCount - 1 do begin
Inc(J, Digits_1(VStr));
end;
VStopwatch.Stop;
Writeln(J, ' ', VStopwatch.ElapsedMilliseconds, ' ms');
J := 0;
VStopwatch := TStopwatch.StartNew;
for I := 0 to cTestCount - 1 do begin
Inc(J, Digits_2(VStr));
end;
VStopwatch.Stop;
Writeln(J, ' ', VStopwatch.ElapsedMilliseconds, ' ms');
J := 0;
VStopwatch := TStopwatch.StartNew;
for I := 0 to cTestCount - 1 do begin
Inc(J, DigitCount(VStr));
end;
VStopwatch.Stop;
Writeln(J, ' ', VStopwatch.ElapsedMilliseconds, ' ms');
end;
begin
try
DoTest;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
{
output:
19000000 813 ms
19000000 133 ms
19000000 171 ms
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.