Skip to content

Instantly share code, notes, and snippets.

@rjnienaber
Last active December 21, 2015 06:09
Show Gist options
  • Save rjnienaber/6261885 to your computer and use it in GitHub Desktop.
Save rjnienaber/6261885 to your computer and use it in GitHub Desktop.
An example of AOP in Ruby using Aquarium
require 'rubygems'
require 'benchmark'
require 'aquarium'
ITERATIONS = 100_000
class MyProcessor
def test_one
1 + 1
end
end
class MySecondProcessor
def test_two
sleep 3
puts "I've awoken!"
end
end
Benchmark.bmbm do |bm|
bm.report('baseline') do
ITERATIONS.times { MyProcessor.new.test_one }
end
end
# Example results
# user system total real
#baseline 0.100000 0.010000 0.110000 ( 0.054000)
class ProcessorTracer
include Aquarium::DSL
around :calls_to => :all_methods, :in_types => MyProcessor,
:method_options => :exclude_ancestor_methods do |jp, object, *args|
jp.proceed
end
around :calls_to => :all_methods, :in_types => /SecondProcessor/,
:method_options => :exclude_ancestor_methods do |jp, object, *args|
start = Time.now
begin
jp.proceed
ensure
puts "Time taken for '#{jp.target_type.name}\##{jp.method_name}': #{Time.now - start}"
end
end
end
puts ""
Benchmark.bmbm do |bm|
bm.report('with AOP') do
ITERATIONS.times { MyProcessor.new.test_one }
end
end
#Example results
# user system total real
#with AOP 0.620000 0.000000 0.620000 ( 0.528000)
#
# Overhead is about 4.7 microseconds per method call
MySecondProcessor.new.test_two
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment