Created
July 28, 2011 09:35
-
-
Save mikbe/1111286 to your computer and use it in GitHub Desktop.
Fiber Creation
This file contains hidden or 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
#!/usr/bin/env ruby | |
#Thread.abort_on_exception = true | |
require 'fiber' | |
require 'benchmark' | |
class FiberRing | |
attr_reader :id | |
def initialize(id) | |
@id = id | |
@fiber = Fiber.new do | |
pass_msg | |
end | |
end | |
def |(nxt) | |
@next = nxt | |
nxt | |
end | |
def resume | |
# puts "@fiber: #{@fiber}" | |
@fiber.resume | |
end | |
def pass_msg | |
while msg = msg_in | |
msg_out msg | |
end | |
end | |
def msg_in | |
unless @next.nil? | |
@next.resume | |
end | |
"#{@id} message" | |
end | |
def msg_out msg | |
Fiber.yield msg | |
end | |
end | |
n = 10000 | |
m = 1 | |
puts "#{n}, #{m}:" | |
tm = Benchmark.bmbm do |bm| | |
3.times do | |
bm.report{ | |
f0 = f = FiberRing.new(0) | |
t = Time.now | |
1.upto(n-1) { |i| f = (f | FiberRing.new(i)) } | |
puts "Creation: #{Time.now - t}" | |
t = Time.now | |
m.times { |j| f0.resume } | |
puts "Execution: #{Time.now - t}" | |
} | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment