1

I have written the following code in ruby to ping a website and check the response. If the response comes true the website is responding well but if false that shows the website is not responding.

require 'net/http'
require 'uri'


def ping(host)
begin
 url=URI.parse(host)
 response=Net::HTTP.get(url)
   if response==""
     return false
   else
     return true
   end
   rescue Errno::ECONNREFUSED
     return false
 end
end

This code works fine but cannot calculate the respose time in which the website responds.

So my question is How to calculate the response time in which the website responds??

Swati Aggarwal
  • 1,225
  • 3
  • 17
  • 34

3 Answers3

5
require 'net/http'
require 'uri'

def ping(host)
  begin
    url = URI.parse(host)
    start_time = Time.now
    response = Net::HTTP.get(url)
    end_time = Time.now - start_time

    if response==""
      return false
    else
      puts "response time : #{end_time}"
      return true
    end

  rescue Errno::ECONNREFUSED
    return false
  end
end

ping "http://www.google.com"

Hope this helps

Shreyas Agarwal
  • 1,088
  • 8
  • 10
1

How about add Time.now after url=URI.parse(host) and after response?

gmaliar
  • 4,796
  • 1
  • 24
  • 34
0

What answers here suggest does not show the server response time, it shows:

  • the time spent in ruby to send the request
  • the network time of the request
  • the server's response time
  • the network time of the response
  • the time spent in ruby to process the response

If you need to see only the time that the server took to process the request you need to do it with another way. You can use the HTTP response headers. The date header in particular can help you with that.

I would suggest to use curl:

response_time_total = `curl -w \"%{time_total}\" google.com -o /dev/null -s`

You can try it out in terminal:

curl -w \"%{time_total}\n\" google.com -o /dev/null -s

There are different metrics you can get like time_namelookup, time_connect, time_starttransfer, time_redirect, etc. Example:

response_times = `curl -w \"%{time_connect}:%{time_starttransfer}:%{time_total}\" google.com -o /dev/null -s`
time_connect, time_starttransfer, time_total = response_times.split(':')

All available metrics and detailed information can be found at the cURL manpage

Refs

How do I get a server's response time?

How do I measure request and response times at once using cURL?

Martin Zinovsky
  • 3,390
  • 1
  • 15
  • 24