我有一个使用 curl 从 ftp 下载文件的小程序。在 CURLOPT_PROGRESSFUNCTION 中传递的函数中,我进行了计算以了解下载速度,问题是下载速度到处跳跃,在 2mbps 的互联网连接上从 512kbps 到 8mbps。而且我无法确定这里出了什么问题。
编辑:我已更改代码以平均读数,curl 下载的问题是您无法预测何时调用 TraceProgress 函数,它可以在不到 1 秒的时间内再次调用,因此程序等待 5 次迭代注意降低读数,并在平均之前取 6 个这样的读数,我还考虑了自上次读数以来经过的时间(秒),因为我们不能保证 TraceProgress 函数将以相等的间隔被调用。
让我知道它现在是否更好看。
这是代码:
int minorCounter = 0;
int majorCounter = 0;
int minorCycle = 4;
int majorCycle = 5;
double blockDL[6];
double blockTime[6];
int TraceProgress( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow )
{
if ( minorCounter == minorCycle )
{
blockDL[majorCounter] = dlnow - oldDownloadNow;
myTimer.Tick();
blockTime[majorCounter] = myTimer.GetDurationInSecs();
minorCounter = 0;
if ( majorCounter == majorCycle )
{
double dl = 0;
double tm = 0;
for ( int i = 0; i < majorCycle ; i++ )
{
dl += blockDL[i];
tm += blockTime[i];
}
dl = dl/(majorCycle+1);
tm = tm/(majorCycle+1);
double currentDownloadSpeed = dl / tm;
/* download speed - divide by 1024 to get speed in kilobytes instead of bytes */
double idownloadSpeed = currentDownloadSpeed / 1024;
string post;
if ( idownloadSpeed > 1024 )
{
idownloadSpeed = idownloadSpeed / 1024;
post = " MB/s";
}
else
{
post = " KB/s";
}
string downloadSpeed = DoubleToString( idownloadSpeed );
size_t x = downloadSpeed.find( "." );
downloadSpeed.erase( x+2 );
downSize = "Download Speed: " + downloadSpeed + post;
SendMessage( hDownloadSpeedSTATIC, WM_SETTEXT, (WPARAM)0, (LPARAM)downSize.c_str() );
majorCounter = 0;
}
else
{
majorCounter++;
}
oldDownloadNow = dlnow;
myTimer.Start();
}
else
{
minorCounter++;
}
return 0;
}