Delphi:如何确定下载速度(kbps)



我用来下载文件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代表千比特而不是千字节之外,我觉得你的代码很好。你有传输的千字节数,传输所需的时间,然后除以这两个值。

这些数字会随着时间的推移而波动。为了平滑这些数字,你可能希望使用移动平均线。

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

服务器,或者你和服务器之间的某个路由器,可能会限制速度,这可以解释为什么即使有其他并发网络流量,你似乎也能得到相同的测量结果。

最新更新