如何在Pascal中加快文件读取速度?
我有以下代码:如何在Pascal中加快文件读取速度?,pascal,Pascal,我有以下代码: program test; var testarray: array [1 .. 100000] of longint; a, b: longint; counter: longint; testf: text; begin assign (testf, 'test.txt'); reset (testf); for counter: = 1 to 10000000 do
program test;
var
testarray: array [1 .. 100000] of longint;
a, b: longint;
counter: longint;
testf: text;
begin
assign (testf, 'test.txt');
reset (testf);
for counter: = 1 to 10000000 do
begin
read (testf, a, b);
testarray [a]: = testarray [a] +1;
testarray [b]: = testarray [b] +1;
end;
close (testf);
end.
test.txt文件如下所示:
6465 74
97 31
98 146
346649
例a=6465 b=74
此时,该程序需要很长时间:
for counter: = 1 to 10000000 do
begin
read (testf, a, b); (* <------ *)
如何提高程序的速度?您应该使用EOF End Of File布尔函数,如果您已到达文本文件的末尾,该函数将返回true,否则返回false。记住这一点,只有在您还没有到达文件末尾时,您才需要阅读接下来的两个数字。因此,当您的while循环使用for循环读取最后一个数字gainst时,它将自动停止。使用此函数不需要计数器变量。我还发现您的代码中存在其他错误:
program test;
var
testarray: array [1 .. 100000] of longint;
a, b: longint;
testf: text;
begin
assign (testf, 'test.txt');
reset (testf);
{ - Using EOF instead of for will speed up your program - }
while not(eof(testf)) do
begin
{ - If you have 2 numbers in each row you shoud use readln - }
readln(testf, a, b);
{ - Correct ": =" to ":=" - }
testarray[a]:= testarray[a] +1;
testarray[b]:= testarray[b] +1;
end;
close (testf);
end.
那么,您可以将计数器的最大值减少10倍,以匹配要开始的数组的大小。数组声明为6个零,循环计数器声明为7。您还可以检查EOF,这样在数据不足时就不会继续循环。你能发布你的真实代码,然后定义长时间意味着什么吗?如果使用Delphi/Turbo Pascal,你可能想试试这个函数。这是一个语法错误。根据@KenWhite注释,您实际运行的循环比数组长度多100倍。因此,实际上,检查EOF并为数组大小定义一个常量,并将其用作最大循环迭代。