Class: PDTP::Server::BandwidthEstimator

Inherits:
Object
  • Object
show all
Defined in:
lib/pdtp/server/bandwidth_estimator.rb

Overview

BandwidthEstimator logs the durations of chunk transfers over time, allowing the server to estimate the bandwidth of individual peers

Defined Under Namespace

Classes: Transfer

Constant Summary collapse

MAXSIZE =

Maximum number of transfers to store in a given history object

100

Instance Method Summary collapse

Constructor Details

#initializeBandwidthEstimator

Returns a new instance of BandwidthEstimator.



48
49
50
51
52
53
# File 'lib/pdtp/server/bandwidth_estimator.rb', line 48

def initialize
  @transfers = []
  
  # Clear caches of all calculated values
  clear_caches
end

Instance Method Details

#estimateObject

Compute an estimate of the bandwidth, culling statistical outliers



70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/pdtp/server/bandwidth_estimator.rb', line 70

def estimate
  return @estimate unless @estimate.nil?
  
  # Prune outliers beyond 2 standard deviations of the mean
  # FIXME maybe this should be 3 standard deviations?
  pruned = estimates.select { |n| (n - estimates_mean).abs < standard_deviation * 2}
  
  # Avoid dividing by zero
  return 0 if pruned.size.zero?
  
  # Calculate the mean of the pruned estimates
  @estimate = pruned.sum / pruned.size
end

#log(start_time, end_time, bytes_transferred) ⇒ Object

Log when a transfer began, ended, and how much data was transferred



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/pdtp/server/bandwidth_estimator.rb', line 56

def log(start_time, end_time, bytes_transferred)
  # Remove an old transfer if we've exceeded MAXSIZE
  @transfers.shift if @transfers.size >= MAXSIZE
  
  # Clear caches of all calculated values because the sample has changed
  clear_caches
  
  # Log the transfer
  @transfers << Transfer.new(start_time, end_time, bytes_transferred)
  
  nil
end