Last active
November 11, 2023 07:03
-
-
Save louishuyng/b58ed695736f276c35ebb0ec150b1792 to your computer and use it in GitHub Desktop.
Ruby Runtime Feature Changes
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
p = Person.new | |
p.refresh # => (...) | |
Person.start_trace | |
p.refresh # => (...) | |
# -> refresh: 0.500 s. | |
Person.end_trace | |
p.refresh # => (...) |
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
class Person | |
TIMED_METHODS = [:refresh, :dup] | |
TIMED_METHODS.each do |method| | |
# set up _without_timing alias of original method | |
alias_method :"#{method}_without_timing", method | |
# set up _with_timing method that wraps the original in timing code | |
define_method :"#{method}_with_timing" do | |
start_time = Time.now.to_f | |
returning(self.send(:"#{method}_without_timing")) do | |
end_time = Time.now.to_f | |
puts "#{method}: #{"%.3f" % (end_time-start_time)} s." | |
end | |
end | |
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
class Person | |
def refresh | |
puts "I am refreshing" | |
end | |
def dup | |
puts "Duplicated" | |
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
class << Person | |
TIMED_METHODS = [:refresh, :dup] | |
def start_trace | |
TIMED_METHODS.each do |method| | |
alias_method method, :"#{method}_with_timing" | |
end | |
end | |
def end_trace | |
TIMED_METHODS.each do |method| | |
alias_method method, :"#{method}_without_timing" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment