Delphi:我如何确定以kbps为单位的下载速度?

Red*_*ber 3 delphi wininet delphi-xe2

我用来下载wininet的一些函数文件:

 Url := source_file;

 destinationfilename := destination_file;
 hInet := InternetOpen(PChar(application.title), INTERNET_OPEN_TYPE_PRECONFIG,
   nil, nil, 0);
 hFile := InternetOpenURL(hInet, PChar(Url), nil, 0,
   INTERNET_FLAG_NO_CACHE_WRITE, 0);

 if Assigned(hFile) then
 begin
   AssignFile(localFile, destinationfilename);
   Rewrite(localFile, 1);
   repeat
     InternetReadFile(hFile, @Buffer, SizeOf(Buffer), bytesRead);
     BlockWrite(localFile, Buffer, bytesRead);
     current_size := current_size + bytesRead;
   until (bytesRead = 0) OR (terminated = True);
   CloseFile(localFile);
   InternetCloseHandle(hFile);
 end;
 InternetCloseHandle(hInet);
Run Code Online (Sandbox Code Playgroud)

我试图确定下载速度,但得到一些奇怪的值:

   ...
   repeat
     QueryPerformanceFrequency(iCounterPerSec);
     QueryPerformanceCounter(T1);

     InternetReadFile(hFile, @Buffer, SizeOf(Buffer), bytesRead);
     BlockWrite(localFile, Buffer, bytesRead);
     current_size := current_size + bytesRead;
     QueryPerformanceCounter(T2);

     _speed := round((bytesRead / 1024) / ((T2 - T1) / iCounterPerSec));

     download_speed := inttostr(_speed) + ' kbps';
   until (bytesRead = 0) OR (terminated = True);
   ...
Run Code Online (Sandbox Code Playgroud)

那么问题是如何确定以kbps为单位的下载速度?提前感谢您的回答!

Rob*_*edy 6

除了缩写kbps是千比特而不是千字节,你的代码看起来很好.您有转移的千字节数,您有转移所花费的时间,并且您将两个值分开.

数字会随着时间的推移而波动.要平滑数字,您可能希望使用移动平均线.

有各种因素可能会影响您的测量.例如,有多层缓冲有效.如果Delphi文件缓冲区很大,那么一些调用BlockWrite只会将内存复制Buffer到维护的内部缓冲区中localFile,而其他调用将包括将缓冲区刷新到磁盘.同样,操作系统可能有文件缓冲区,有时只能写入.因此,您不仅要测量下载速度,还要测量磁盘I/O速度.增加大小Buffer将减少效果,因为您更有可能在每次迭代时耗尽文件缓冲区.移动平均线将抵消累积和冲洗缓冲区引入的变化.

服务器或您与服务器之间的某个路由器可能会限制速度,这可以解释为什么即使存在其他并发网络流量,您也可以获得相同的测量结果.