Posted By

Shamaoke on 01/12/11


Tagged

ruby benchmark ring


Versions (?)

Ring Benchmark


 / Published in: Ruby
 

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.

  1. # encoding: utf-8
  2.  
  3. require 'benchmark'
  4.  
  5. class Node
  6. @@number = 0
  7.  
  8. def initialize(attach = nil)
  9. @attach = attach
  10. @fiber = Fiber.new { pass_number }
  11. end
  12.  
  13. def pass_number
  14. loop do
  15. @attach ? @@number = @attach.resume.succ
  16. : @@number = @@number.succ
  17. Fiber.yield @@number
  18. end
  19. end
  20.  
  21. def resume
  22. @fiber.resume
  23. end
  24.  
  25. def reset_number
  26. @@number = 0
  27. end
  28. end
  29.  
  30. class Gauge
  31. def initialize
  32. @nodes = $*[0].to_i
  33. @cycles = $*[1].to_i
  34. create_ring
  35. end
  36.  
  37. def create_ring
  38. if @nodes <= 1
  39. raise ArgumentError, 'the node quantity should be greater than 1'
  40. else
  41. @nodes.times do
  42. @ring ? @ring = Node.new(@ring)
  43. : @ring = Node.new
  44. end
  45. end
  46. end
  47.  
  48. def run
  49. time = Benchmark.measure do
  50. @cycles.times { @ring.resume }
  51. end.format('%.3r').gsub!(/\(|\)/, '')
  52. puts time
  53. @ring.reset_number
  54. end
  55.  
  56. def self.start
  57. new.run
  58. end
  59. end
  60.  
  61. Gauge.start

Report this snippet  

You need to login to post a comment.