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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed. The only failed require appears to be
fastthread
which incurs ~0.09 seconds.