Created
May 10, 2012 15:09
-
-
Save mscottford/2653763 to your computer and use it in GitHub Desktop.
A way to measure how long it takes Rails to boot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'date' | |
require 'open3' | |
require 'timeout' | |
require 'socket' | |
class AppBootBenchmark | |
RAILS_PORT = 9191 | |
def initialize(options = {}) | |
@stream_output = options[:stream_output] | |
end | |
def call | |
# start the clock | |
start_time = Time.now.to_f | |
# start rails in a forked child process running on port 9191 | |
input, output, error, thread = Open3.popen3 "rails server thin -p #{RAILS_PORT}" | |
if @stream_output | |
Thread.new do | |
until output.closed? | |
buffer = output.readpartial(1024) | |
STDOUT.write(buffer) | |
end | |
end | |
Thread.new do | |
until error.closed? | |
buffer = error.readpartial(1024) | |
STDERR.write(buffer) | |
end | |
end | |
end | |
# wait until port 9191 is accepting connections | |
until booted? | |
sleep 0.1 | |
end | |
# stop the clock | |
stop_time = Time.now.to_f | |
# send the child process a SIGKILL | |
Process.kill("TERM", thread.pid) | |
puts "%.3fs" % (stop_time - start_time) | |
end | |
private | |
def booted? | |
is_port_bound?('127.0.0.1', RAILS_PORT) | |
end | |
# based on http://stackoverflow.com/a/517638/243215 | |
def is_port_bound?(ip, port) | |
begin | |
Timeout::timeout(1) do | |
begin | |
s = TCPSocket.new(ip, port) | |
s.close | |
return true | |
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH | |
return false | |
end | |
end | |
rescue Timeout::Error | |
end | |
return false | |
end | |
end | |
AppBootBenchmark.new.call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment