Skip to content

Instantly share code, notes, and snippets.

@postmodern
Created March 10, 2011 05:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postmodern/863597 to your computer and use it in GitHub Desktop.
Save postmodern/863597 to your computer and use it in GitHub Desktop.
Benchmark each require in your Ruby code.
require 'rubygems'
require 'rbtree'
class Req
attr_accessor :path, :time, :requires, :exception
def initialize(path)
@path = path
@requires = []
@time = 0
end
end
module Kernel
@@require_stack = [ Req.new('<top>') ]
alias original_require require
def require(path)
req = Req.new(path)
@@require_stack.last.requires.push(req)
@@require_stack.push req
result = nil
t1 = Time.now
begin
result = original_require(path)
rescue LoadError => e
req.exception = e
end
t2 = Time.now
req.time = (t2 - t1)
@@require_stack.pop
unless req.exception
result
else
raise(req.exception)
end
end
def print_require_tree(req, loaded, level = 0)
indent = ' ' * level
fmt = " #{loaded[req.path] ? '(%10.5f)' : ' %10.5f '} #{indent}%s %s"
puts fmt % [ req.time, req.path, req.exception ? "(#{req.exception.message})" : '' ]
loaded[req.path] = true
req.requires.each do |r|
print_require_tree(r, loaded, level + 1)
end
end
at_exit do
print_require_tree(@@require_stack.first, {})
end
end
require 'rubygems'
module Kernel
@@require_times = {}
alias original_require require
def require(path)
t1 = Time.now
result = original_require(path)
t2 = Time.now
@@require_times[path] = (t2 - t1)
result
end
at_exit do
@@require_times.sort_by { |path,t| t }.each do |path,t|
puts " #{t}\t#{path}"
end
end
end
@dkubb
Copy link

dkubb commented Mar 10, 2011

One suggestion I'd have for require_benchmark.rb is that you only track the require times when result is true.

If you mistakenly require something twice, the second time the result will be false and you'll overwrite the original time you tracked. Since a second require should be lightening fast, due to ruby caching the fact that it was required, it could be changing the benchmark to make it look like the file loads way faster than it does in reality.

@postmodern
Copy link
Author

Fixed. The only failed require appears to be fastthread which incurs ~0.09 seconds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment