通过取发送字节的5倍的平均值来计算发送文件速度/秒
本文关键字:文件 计算 速度 5倍 字节 平均值 | 更新日期: 2023-09-27 18:21:49
im尝试使用平均值计算每秒传输文件速度
我每秒5次获取发送的字节数sum和prevSum之间的差异
我很困惑,因为每次有一点变化,速度值就会变化。。正确的解决方案是什么??
static long prevSum = 0;
static long[] rate = new long[5];
private static void SpeedPerSec(object o)
{
fileProgress fP = (fileProgress)o; //get the form conrtols
while (busy) // while sending file is active
{
for (int i = 0; i < rate.Length; i++)
{
//diff between the sent bytes and prev sent bytes
rate[i] = (sum - prevSum);
Thread.Sleep(1000/rate.Length);
}
prevSum = sum;
fP.RateLabel(Convert.ToInt64(rate.Average()));
//print the trasnfer rate which take a long value .. it just print the value in MB or KB string
}
}
这是sendFile代码:
public static bool busy = false;
public static Socket client;
public static int packetSize = 1024*8;
public static int count = 0;
public static long fileSize;
public static long sum = 0;
public static void sendFile(string filePath)
{
// run the progres Form
Thread thFP = new Thread(fpRUN);
fileProgress fP = new fileProgress("Sending...");
thFP.Start(fP);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
string fileName = Path.GetFileName(filePath);
byte[] fileData;
try
{
//sending file name and file size to the server
busy = true;
fileSize = fs.Length;
byte[] fileDetial = null;
string detail = fileName + "," + fileSize.ToString();
fileDetial = Encoding.ASCII.GetBytes(detail);
client.Send(fileDetial);
//sending file data to the server
fileData = new byte[packetSize];
count = 0;
sum = 0;
Thread thSpeed = new Thread(SpeedAndTimeLeft); //*here the thread of SPEED per second method
thSpeed.Start(fP);
fP.SizeLabel(fileSize); // tell the form the file size
Thread thClock = new Thread(fP.clock);
thClock.Start();
while (sum < fileSize)
{
fs.Seek(sum, SeekOrigin.Begin);
fs.Read(fileData, 0, fileData.Length);
count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
sum += count;
fP.ProgressBarFileHandler(sum,fileSize); //progressbar value
fP.SentLabel(sum, fileSize); //tell the form how much sent }
}
finally
{
busy = false;
fs.Close();
fileData = null;
MessageBox.Show(string.Format("{0} sent successfully", fileName));
}
}
我不明白为什么要使用long[]速率变量。。。如果你想计算传输速率并每秒更新一次,你应该将当前的fileSize存储在一个变量中,然后在睡眠后查看新的fileSize。然后从新文件中减去上一个文件Sieze,就得到了最后一秒的传输速率(实时传输速率)。对于一般传输速率,您应该在下载/上传开始时取一个时间戳来计算它,然后在每次睡眠后,通过将当前fileSize除以到目前为止经过的总秒数来计算速率。
您可以用这种方式计算平均值,而不是每次都计算平均值(如果您的rate数组变得非常大,这可能会变得很慢)。
考虑到你的利率是这些,为了这个例子
long[] rates = new long[] { 5, 1, 3,4 ,2 ,5, 1};
你可以这样计算每一步的平均值:
double currentAverage = 0;
for (int i = 0; i < rates.Length; i++)
{
long currentRate = rates[i];
int iteration = i + 1;
currentAverage = (currentAverage * i + currentRate) / iteration;
}
然后对每个速率采样等待一秒钟。