Search code examples
ruby-on-rails-3curlresponse-time

Rails get response time for a curl (JSON) request


In my app do I multiple request to an external server like this:

    req = Curl::Easy.new do |curl| 
        curl.url = "https://www.mysite.com"
        curl.headers['Content-type'] = 'application/json'
    end
    req.perform

It is possible to retrieve the response time (how long takes the request)?

A solution that I think is working is the following (pseudocode), but there is something more elegant?

    req = Curl::Easy.new do |curl| 
        curl.url = "https://www.mysite.com"
        curl.headers['Content-type'] = 'application/json'
    end

    timeBefore = Time.now
    req.perform
    timeAfter = Time.now
    responseTime = timeAfter - timeBefore

Solution

  • You can use Ruby's Benchmark module as follows:

    time = Benchmark.realtime do
          req.perform
    end
    puts "Time elapsed #{time*1000} milliseconds"