我用来下载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为单位的下载速度?提前感谢您的回答!
答案 0 :(得分:6)
除了缩写 kbps 是千位而不是千字节之外,您的代码对我来说很好。你有转移的千字节数,你有转移的时间,你划分这两个值。
这些数字会随着时间的推移而波动。要平滑数字,您可能希望改为使用moving average。
有多种因素可能会影响您的测量结果。例如,有多层缓冲有效。如果Delphi文件缓冲区很大,那么对BlockWrite
的一些调用只会将内存从Buffer
复制到为localFile
维护的内部缓冲区,而其他调用将包括将缓冲区刷新到磁盘。同样,操作系统可能有文件缓冲区,有时只能写入。因此,您不仅要测量下载速度,还要测量磁盘I / O速度。增加Buffer
的大小会减少效果,因为您更有可能在每次迭代时耗尽文件缓冲区。移动平均线将抵消累积和冲洗缓冲区引起的变化。
服务器或您与服务器之间的某个路由器可能会限制速度,这可以解释为什么即使存在其他并发网络流量,您似乎也可以获得相同的测量结果。