This script creates a ring of arbitrary number of nodes. Every node except the last one have a link to the next created node. The number of nodes is specified through the command line argument. There's a number which is transfered from one node to another. Every time that number is increased by 1. When the program reaches the last node it transfers the control back to the first node (if a second command line argument is greater than 1). The program continues to transfer the number round the ring and increase its value. After it finishes to run the number through the ring it prints out the time of that work.
This script is based on fibers — a Ruby realisation of so-called coroutines. It can serve as an example which demonstrates how fibers works.
# encoding: utf-8 require 'benchmark' class Node @@number = 0 def initialize(attach = nil) @attach = attach @fiber = Fiber.new { pass_number } end def pass_number loop do @attach ? @@number = @attach.resume.succ : @@number = @@number.succ Fiber.yield @@number end end def resume @fiber.resume end def reset_number @@number = 0 end end class Gauge def initialize @nodes = $*[0].to_i @cycles = $*[1].to_i create_ring end def create_ring if @nodes <= 1 raise ArgumentError, 'the node quantity should be greater than 1' else @nodes.times do @ring ? @ring = Node.new(@ring) : @ring = Node.new end end end def run time = Benchmark.measure do @cycles.times { @ring.resume } end.format('%.3r').gsub!(/\(|\)/, '') puts time @ring.reset_number end def self.start new.run end end Gauge.start
You need to login to post a comment.
