1

I am using RestClient gem to execute API request. I want to get how much time taken in execute that request.

responseObject = RestClient.post request_url,params[:request_body],:content_type => params[:content_type]
responseObject.code

now how can I get execution time.

jayesh
  • 2,422
  • 7
  • 44
  • 78

2 Answers2

2

Use benchmark for that purpose.

require "benchmark"

time = Benchmark.measure do
  responseObject = RestClient.post request_url,params[:request_body],:content_type => params[:content_type]     
end

Else in a primitive way:

beginning_time = Time.now
responseObject = RestClient.post request_url,params[:request_body],:content_type => params[:content_type]
end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"
shivam
  • 16,048
  • 3
  • 56
  • 71
2

alias_method_chain can be useful here.

Since RestClient is using a class called Request to execute all api requests (see source code here), you can add this snippet in an initializer to your rails project. Just add a config.debug_rest_client_duration = true in your environment config and it will work.

class RestClient::Request

  class << self
    def execute_with_log_duration(args, &block)
      started = Time.now
      res = execute_without_log_duration(args, &block)
      Rails.logger.info "api call duration is: " + (Time.now - started).to_s + " seconds"
      return res
    end
    alias_method_chain :execute, :log_duration if Rails.application.config.debug_rest_client_duration
  end

end
Community
  • 1
  • 1
Ronna
  • 1,150
  • 14
  • 24