我通过PHP ftp_
函数连接到服务器。
如何测量传输速度?
答案 0 :(得分:6)
使用非阻塞ftp函数下载文件并计算时间和文件大小差异。下面是一个带指数平滑的简单演示,可以防止速度过快跳过:
define('ALPHA', 0.2); // Weight factor of new calculations, between 0 and 1
$ftp = ftp_connect(...);
$tmp = ftp_nb_get($ftp, $filename, $filename, FTP_BINARY);
$transferred = 0;
$rate = 0;
$time = microtime(true);
while ($tmp == FTP_MOREDATA) {
$tmp = ftp_nb_continue($ftp);
$timeNow = microtime(true);
$sizeNow = filesize($filename);
$currentRate = ($sizeNow - $transferred) / ($timeNow - $time);
$rate = ALPHA * $currentRate + (1 - ALPHA) * $rate;
$time = $timeNow;
$transferred = $sizeNow;
echo "Current transfer speed: $rate B/s\n";
}
如果您希望上传ftp_nb_put()
同样的内容,则必须将filesize($filename)
替换为ftp_size($ftp2,$filename)
,其中$ftp2
必须是第二个相同的连接,使用只是要询问远程文件的大小,因为ftp_size()
无法与您的主连接一起使用,而非阻塞传输正在进行中。
答案 1 :(得分:2)
这就是我对phihag的代码进行野蛮化以检查非阻塞上传速度的方法。当非阻塞传输正在进行时,您无法使用ftp_size()
,因此您只需为此目的而建立辅助连接。我显示当前速度,平均速度,经过时间和估计剩余时间。
$primary_connection = ftp_connect($server);
$secondary_connection = ftp_connect($server);
$mode = FTP_BINARY;
$login = ftp_login($primary_connection, $ftp_user_name, $ftp_user_pass);
$login2 = ftp_login($secondary_connection, $ftp_user_name, $ftp_user_pass);
if (!$primary_connection || !$login) { die('Connection attempt failed!'); }
ftp_pasv($primary_connection,TRUE);
ftp_pasv($secondary_connection,TRUE);
$upload_status=ftp_nb_put($primary_connection, $destination_file, $source_file, $mode);
define('ALPHA', 0.2); // Weight factor of new calculations, between 0 and 1
$filesize=filesize($source_file);
$transferred = 0;
$rate = 0;
$time = microtime(true);
$start_time=$time;
while($upload_status == FTP_MOREDATA){
$upload_status = ftp_nb_continue($primary_connection);
$sizeNow=ftp_size($secondary_connection,$destination_file);
$sizeNowkB=$sizeNow/1024;
$timeNow = microtime(true);
$currentRate = ($sizeNow - $transferred) / ($timeNow - $time);
$currentkBRate = $currentRate / 1024;
$rate = ALPHA * $currentRate + (1 - ALPHA) * $rate;
$time = $timeNow;
$transferred = $sizeNow;
printf("Uploading file: %s",$source_file);
echo "<br>\n";
printf( "To be transferred: %0.2f kB", $filesize/1024);
echo "<br>\n";
printf( "Transferred: %0.2f kB", $sizeNowkB);
echo "<br>\n";
printf( "Current speed: %0.2f kB/s", $currentkBRate);
echo "<br>\n";
printf( "Average speed: %0.2f kB/s", $rate/1024);
echo "<br>\n";
$elapsed_time=$timeNow - $start_time;
printf( "Elapsed time: %0.2f s", $elapsed_time);
echo "<br>\n";
if($rate!=0){
$eta=$filesize/$rate - $elapsed_time;
}else{
$eta=0.0;
}
if($eta<=0){
$eta=0.0;
};
printf( "Estimated time left: %0.2f s", $eta);
echo "<br>\n";
}
答案 2 :(得分:1)
ftp
函数示例:
$start = mktime(); // 1
$size = filesize('yourfile.txt') / 1024 ; // 2 <- to get the KB
... do your transfer... // 3
//after ftp transfer
$stop = mktime(); // 4
$duration = $stop - $start;
$speed = $size / $duration; // 5
这基本上为您提供转移后的速度。如果您想在转移时获得速度,还有其他方法可以实现。