Created
May 9, 2010 21:07
-
-
Save Mikoangelo/395409 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EventList | |
Event = Struct.new :type, :time | |
attr_reader :events | |
def initialize | |
@events = [] | |
end | |
def push type, time | |
@events.push Event.new type, time | |
end | |
def next | |
@events = @events.sort_by &:time | |
@events.shift | |
end | |
end | |
class Host | |
attr_reader :packets_dropped, :event_list | |
attr_reader :buffer_length, :buffer_maximum | |
def initialize mu, lambda, buffer_maximum = nil | |
@mu, @lambda = mu, lambda | |
@event_list = EventList.new | |
@buffer_maximum = buffer_maximum | |
@time = 0.0 | |
@buffer_length = @packets_dropped = 0 | |
@last_departure = @time_previous = 0.0 | |
@utilization = @buffer_stat = 0.0 | |
arrival # seed the first arrival | |
end | |
def nedt rate | |
-1 / rate * Math.log(1 - rand) | |
end | |
def arrival | |
event_list.push :arrival, @time + nedt(@lambda) # schedule the next arrival | |
if buffer_free? | |
@last_departure = next_departure | |
event_list.push :departure, @last_departure # schedule the departure for this packet | |
@buffer_length += 1 | |
else | |
@packets_dropped += 1 | |
end | |
end | |
def departure | |
@buffer_length -= 1 | |
end | |
def next_departure | |
[@time, @last_departure].max + nedt(@mu) | |
end | |
def buffer_free? | |
!@buffer_maximum or @buffer_length <= @buffer_maximum | |
end | |
def buffer_used? | |
@buffer_length > 0 | |
end | |
def process_event | |
event = event_list.next | |
@time = event.time | |
gather_statistics | |
@time_previous = @time; | |
send event.type | |
end | |
def gather_statistics | |
@utilization += @time - @time_previous if buffer_used? | |
@buffer_stat += @buffer_length * (@time - @time_previous); | |
end | |
def server_utilization | |
@utilization / @time * 100 | |
end | |
def mean_buffer_length | |
@buffer_stat / @time | |
end | |
end | |
host = Host.new 1, 0.3, 1 | |
100_000.times do | |
host.process_event | |
end | |
puts "Server utilization: #{host.server_utilization}" | |
puts "Mean buffer length: #{host.mean_buffer_length}" | |
puts "Dropped packets: #{host.packets_dropped}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment