cs-codex-dist-tests/ProjectPlugins/CodexPlugin/TransferSpeeds.cs

68 lines
2.0 KiB
C#
Raw Normal View History

2023-12-06 08:59:45 +00:00
using Utils;
namespace CodexPlugin
{
public interface ITransferSpeeds
{
2023-12-06 09:50:02 +00:00
BytesPerSecond? GetUploadSpeed();
BytesPerSecond? GetDownloadSpeed();
2023-12-06 08:59:45 +00:00
}
public class TransferSpeeds : ITransferSpeeds
{
private readonly List<BytesPerSecond> uploads = new List<BytesPerSecond>();
private readonly List<BytesPerSecond> downloads = new List<BytesPerSecond>();
public void AddUploadSample(ByteSize bytes, TimeSpan duration)
{
uploads.Add(Convert(bytes, duration));
}
public void AddDownloadSample(ByteSize bytes, TimeSpan duration)
{
downloads.Add(Convert(bytes, duration));
}
2023-12-06 09:50:02 +00:00
public BytesPerSecond? GetUploadSpeed()
2023-12-06 08:59:45 +00:00
{
2023-12-06 09:50:02 +00:00
if (!uploads.Any()) return null;
return uploads.Average();
2023-12-06 08:59:45 +00:00
}
2023-12-06 09:50:02 +00:00
public BytesPerSecond? GetDownloadSpeed()
2023-12-06 08:59:45 +00:00
{
2023-12-06 09:50:02 +00:00
if (!downloads.Any()) return null;
return downloads.Average();
2023-12-06 08:59:45 +00:00
}
private static BytesPerSecond Convert(ByteSize size, TimeSpan duration)
{
double bytes = size.SizeInBytes;
double seconds = duration.TotalSeconds;
return new BytesPerSecond(System.Convert.ToInt64(Math.Round(bytes / seconds)));
}
2023-12-06 09:50:02 +00:00
}
2023-12-06 08:59:45 +00:00
2023-12-06 09:50:02 +00:00
public static class ListExtensions
{
public static BytesPerSecond Average(this List<BytesPerSecond> list)
2023-12-06 08:59:45 +00:00
{
double sum = list.Sum(i => i.SizeInBytes);
double num = list.Count;
2023-12-06 09:50:02 +00:00
return new BytesPerSecond(Convert.ToInt64(Math.Round(sum / num)));
}
public static BytesPerSecond? OptionalAverage(this List<BytesPerSecond?>? list)
{
if (list == null || !list.Any() || !list.Any(i => i != null)) return null;
var values = list.Where(i => i != null).Cast<BytesPerSecond>().ToArray();
double sum = values.Sum(i => i.SizeInBytes);
double num = values.Length;
return new BytesPerSecond(Convert.ToInt64(Math.Round(sum / num)));
2023-12-06 08:59:45 +00:00
}
}
}