如何加快Pascal中的文件读取速度?

时间:2014-01-15 20:46:06

标签: 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 
          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

346 649

例如a = 6465 b = 74

此程序需要很长时间:

for counter: = 1 to 10000000 do 
          begin 
              read (testf, a, b); (* <------ *)

如何加快程序的速度?

1 个答案:

答案 0 :(得分:0)

你应该使用 EOF (文件结束)布尔函数,如果你到达了文本文件的末尾,它将返回 true ,否则 false 。考虑到这一点,只有在尚未到达文件末尾时才必须读取下两个数字。因此, while循环会在读取最后一个数字时自动停止(与 for循环相对)。使用此功能,您不需要计数器变量。我还在您的代码中发现了其他错误:

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.