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

标签 delphi delphi-xe2 wininet

我使用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);

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

   ...
   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);
   ...

所以问题是我如何确定下载速度(以 kbps 为单位)?预先感谢您的回答!

最佳答案

除了缩写 kbps 代表千位而不是千字节之外,您的代码对我来说看起来不错。您有传输的千字节数、传输所需的时间,然后将这两个值相除。

数字会随着时间的推移而波动。为了平滑数字,您可能希望使用 moving average相反。

有多种因素可能会影响您的测量结果。例如,实际上存在多层缓冲。如果 Delphi 文件缓冲区很大,则对 BlockWrite 的某些调用将只是将内存从 Buffer 复制到为 localFile 维护的内部缓冲区中,而其他调用将包括将缓冲区刷新到磁盘。同样,操作系统可能具有仅有时被写入的文件缓冲区。因此,您不仅要测量下载速度,还要测量磁盘 I/O 速度。增加 Buffer 的大小会减轻影响,因为您更有可能在每次迭代中耗尽文件缓冲区。移动平均线可以抵消累积和刷新缓冲区带来的变化。

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

关于Delphi:我如何确定下载速度(以kbps为单位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13934746/

相关文章:

delphi - TListView 记录按需加载

delphi - 禁止RemObjects SOAP错误“未预期内容类型”

delphi - 如何在 Firemonkey stringgrid 单元格中使用不同的字体样式和图标

winapi - 如何使用 WinInet 发送 HTTPS 请求?

firefox - 如何让 Fiddler 不自动代理 WinINET 连接?

Delphi - 查找正在从我的程序访问文件的进程

json - 在 Datasnap (Delphi 10) 中旋转数据集 JSON 结果

delphi - 如何在 Delphi 中以结果记录退出?

c++ - HttpSendRequest 未正确发布

delphi - 如何在IMAP邮箱中搜索特定的电子邮件?