Skip to content

Instantly share code, notes, and snippets.

@zedxxx
Last active July 13, 2019 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zedxxx/6baf6e0467ae1e60237fc3a194f47ec4 to your computer and use it in GitHub Desktop.
Save zedxxx/6baf6e0467ae1e60237fc3a194f47ec4 to your computer and use it in GitHub Desktop.
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