Skip to content

Instantly share code, notes, and snippets.

@afrazkhan
Last active March 17, 2020 12:15
Show Gist options
  • Save afrazkhan/ce89988f80962744511f135ec5df9cdb to your computer and use it in GitHub Desktop.
Save afrazkhan/ce89988f80962744511f135ec5df9cdb to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "optparse"
require "net/http"
require "benchmark"
options = {}
opt_parse = OptionParser.new do |opts|
opts.banner = "Usage: reponse_times.rb [options]"
opts.on("-u", "--url URL", "URL to collect response times for") do |u|
options[:url] = u
end
opts.on("-d", "--duration DURATION", "Time in minutes to collect response times for") do |d|
options[:duration] = d
end
opts.on_tail("-h", "--help", "This :)") do
puts opts
exit
end
end
opt_parse.parse!
if options[:url].nil? || options[:duration].nil?
puts ("All options are mandatory, see --help")
exit(-1)
end
def measure_response_times(location, minutes)
# Make a GET call to [location] for duration of [minutes], and record their response times
# Return an array with all the measured times on success, and a failure string on failure
seconds = (minutes * 60).to_i
times = []
begin
countdown_thread = Thread.new do
seconds.downto(1) do
sleep 1
end
end
while countdown_thread.alive?
response_time = Benchmark.measure do
Net::HTTP.get_response(URI(location))
end
puts response_time.real
times.append(response_time.real)
sleep 1
end
return times
rescue SocketError => error
return "Couldn't GET #{location}: #{error}"
end
end
def create_report(times)
# From an array of [times], make a report of min, max, and average
# Return a string with the report on success, or a string with an error message on failure
if times.class != Array
return "The [times] variable to create_report() must be an array. Recieved: #{times}"
end
begin
return "\n" \
"Slowest: #{times.max}\n" \
"Fastest: #{times.min}\n" \
"Average: #{times.sum() / times.size}\n"
rescue NoMethodError => error
return "Couldn't create a report: #{error}"
end
end
times = measure_response_times(options[:url], options[:duration].to_f)
puts(create_report(times))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment