Class: Bench
- Inherits:
-
Object
- Object
- Bench
- Defined in:
- lib/analyzer_tools/bench.rb
Overview
Bench measures load time for a particular page. You can run it multi-threaded to test web server performance, or single threaded to test the performance of a single page.
Instance Method Summary collapse
-
#do_request ⇒ Object
Performs a request.
-
#initialize(uri, requests, threads = 1) ⇒ Bench
constructor
Creates a new Bench instance that will
requests
fetches ofuri
usingthread
concurrent threads. -
#run ⇒ Object
Starts the benchmark.
-
#time ⇒ Object
Returns the amount of time taken to execute the given block.
-
#time_request ⇒ Object
Returns the time taken to perform a request.
Constructor Details
#initialize(uri, requests, threads = 1) ⇒ Bench
Creates a new Bench instance that will requests
fetches of uri
using thread
concurrent threads.
16 17 18 19 20 21 22 23 24 |
# File 'lib/analyzer_tools/bench.rb', line 16 def initialize(uri, requests, threads = 1) raise ArgumentError, "Thread count must be more than 0" if threads < 1 @uri = uri @total_requests = requests @tenths = @total_requests > 10 ? @total_requests / 10 : 1 @hundredths = @total_requests > 100 ? @total_requests / 100 : 1 @num_requests = requests @threads = threads end |
Instance Method Details
#do_request ⇒ Object
Performs a request.
65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/analyzer_tools/bench.rb', line 65 def do_request s = TCPSocket.new @uri.host, @uri.port s.puts "GET #{@uri.request_uri} HTTP/1.0\r\n" s.puts "Host: #{@uri.host}\r\n" s.puts "User-Agent: RubyBench\r\n" s.puts "\r\n" s.flush response = s.read ensure s.close unless s.nil? end |
#run ⇒ Object
Starts the benchmark. Returns an Array of request times in seconds.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/analyzer_tools/bench.rb', line 29 def run done = false times = [] threads = ThreadGroup.new count_m = Mutex.new @threads.times do Thread.start do threads.add Thread.current until @num_requests <= 0 do count_m.synchronize do if @num_requests % @tenths == 0 then print @num_requests elsif @num_requests % @hundredths == 0 then print '.' end @num_requests -= 1 end $stdout.flush times << time_request end end Thread.pass end threads.enclose threads.list.each { |t| t.join } puts return times end |
#time ⇒ Object
Returns the amount of time taken to execute the given block.
80 81 82 83 84 85 |
# File 'lib/analyzer_tools/bench.rb', line 80 def time start_time = Time.now.to_f yield end_time = Time.now.to_f return end_time - start_time end |
#time_request ⇒ Object
Returns the time taken to perform a request.
90 91 92 93 94 |
# File 'lib/analyzer_tools/bench.rb', line 90 def time_request time do do_request end end |