summaryrefslogtreecommitdiff
path: root/lib/irb/init.rb
diff options
context:
space:
mode:
authoraycabta <aycabta@gmail.com>2020-08-15 06:36:24 +0900
committeraycabta <aycabta@gmail.com>2020-12-20 16:23:59 +0900
commit9f08e3c703795e81d333d568e7e44743022468f1 (patch)
treefe9a2ae21291561130f584ef6c2bb9f5700b53d1 /lib/irb/init.rb
parent8b6aaeaddf2d13833c0540490a84741035a3a808 (diff)
[ruby/irb] Add measure command
You can use "measure" command to check performance in IRB like below: irb(main):001:0> 3 => 3 irb(main):002:0> measure TIME is added. => nil irb(main):003:0> 3 processing time: 0.000058s => 3 irb(main):004:0> measure :off => nil irb(main):005:0> 3 => 3 You can set "measure :on" by "IRB.conf[:MEASURE] = true" in .irbrc, and, also, set custom performance check method: IRB.conf[:MEASURE_PROC][:CUSTOM] = proc { |context, code, line_no, &block| time = Time.now result = block.() now = Time.now puts 'custom processing time: %fs' % (Time.now - time) if IRB.conf[:MEASURE] result } https://github.com/ruby/irb/commit/3899eaf2e2
Diffstat (limited to 'lib/irb/init.rb')
-rw-r--r--lib/irb/init.rb55
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/irb/init.rb b/lib/irb/init.rb
index 73ef420e60..f17d316c43 100644
--- a/lib/irb/init.rb
+++ b/lib/irb/init.rb
@@ -111,11 +111,66 @@ module IRB # :nodoc:
@CONF[:CONTEXT_MODE] = 4 # use a copy of TOPLEVEL_BINDING
@CONF[:SINGLE_IRB] = false
+ @CONF[:MEASURE] = false
+ @CONF[:MEASURE_PROC] = {}
+ @CONF[:MEASURE_PROC][:TIME] = proc { |context, code, line_no, &block|
+ time = Time.now
+ result = block.()
+ now = Time.now
+ puts 'processing time: %fs' % (now - time) if IRB.conf[:MEASURE]
+ result
+ }
+ @CONF[:MEASURE_PROC][:STACKPROF] = proc { |context, code, line_no, &block|
+ success = false
+ begin
+ require 'stackprof'
+ success = true
+ rescue LoadError
+ puts 'Please run "gem install stackprof" before measuring by StackProf.'
+ end
+ if success
+ result = nil
+ stackprof_result = StackProf.run(mode: :cpu) do
+ result = block.()
+ end
+ StackProf::Report.new(stackprof_result).print_text if IRB.conf[:MEASURE]
+ result
+ else
+ block.()
+ end
+ }
+ @CONF[:MEASURE_CALLBACKS] = []
+
@CONF[:LC_MESSAGES] = Locale.new
@CONF[:AT_EXIT] = []
end
+ def IRB.set_measure_callback(type = nil)
+ added = nil
+ if type
+ type_sym = type.upcase.to_sym
+ if IRB.conf[:MEASURE_PROC][type_sym]
+ added = [type_sym, IRB.conf[:MEASURE_PROC][type_sym]]
+ end
+ elsif IRB.conf[:MEASURE_PROC][:CUSTOM]
+ added = [:CUSTOM, IRB.conf[:MEASURE_PROC][:CUSTOM]]
+ else
+ added = [:TIME, IRB.conf[:MEASURE_PROC][:TIME]]
+ end
+ IRB.conf[:MEASURE_CALLBACKS] << added if added
+ added
+ end
+
+ def IRB.unset_measure_callback(type = nil)
+ if type.nil?
+ IRB.conf[:MEASURE_CALLBACKS].clear
+ else
+ type_sym = type.upcase.to_sym
+ IRB.conf[:MEASURE_CALLBACKS].reject!{ |t, c| t == type_sym }
+ end
+ end
+
def IRB.init_error
@CONF[:LC_MESSAGES].load("irb/error.rb")
end