Created
March 10, 2011 05:04
-
-
Save postmodern/863597 to your computer and use it in GitHub Desktop.
Benchmark each require in your Ruby code.
This file contains 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 '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 |
This file contains 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 '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 |
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
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.