Posted By

Shamaoke on 07/07/11


Tagged

ruby Multithreading


Versions (?)

Ruby. Thread benchmark


 / Published in: Ruby
 

Connect to three sites using threads and without using them. Fetch the response. Measure the benchmark.

  1. # encoding: utf-8
  2.  
  3. require 'net/http'
  4. require 'benchmark'
  5.  
  6. class StatusFetcher
  7. attr_reader :result
  8.  
  9. def initialize
  10. @result = []
  11. end
  12.  
  13. def self.start!
  14. new
  15. end
  16. end
  17.  
  18. class ThreadStatusFetcher < StatusFetcher
  19. def initialize
  20. super
  21. threads = []
  22. %w{ stackoverflow.com
  23. superuser.com
  24. systemfault.com
  25. }.each do |page|
  26. threads << Thread.new(page) do |url|
  27. http = Net::HTTP.new(url, 80)
  28. @result << "#{url}: #{http.get('/').message}"
  29. end
  30. end
  31. threads.each(&:join)
  32. end
  33. end
  34.  
  35. class SimpleStatusFetcher < StatusFetcher
  36. def initialize
  37. super
  38. %w{ stackoverflow.com
  39. superuser.com
  40. systemfault.com
  41. }.each do |url|
  42. http = Net::HTTP.new(url, 80)
  43. @result << "#{url}: #{http.get('/').message}"
  44. end
  45. end
  46. end
  47.  
  48. Benchmark.bm(8) do |r|
  49. r.report('simple') { SimpleStatusFetcher.start!.result }
  50. r.report('thread') { ThreadStatusFetcher.start!.result }
  51. end

Report this snippet  

You need to login to post a comment.