Skip to content

Instantly share code, notes, and snippets.

@gnarg
Created November 6, 2012 07:38
Show Gist options
  • Save gnarg/4023276 to your computer and use it in GitHub Desktop.
Save gnarg/4023276 to your computer and use it in GitHub Desktop.
Demo of light weight database futures
require 'benchmark'
ENV['RAILS_ENV'] ||= 'development'
require_relative 'config/environment'
class DeferredQuery
def initialize(query)
@thread = Thread.new do
ActiveRecord::Base.connection_pool.with_connection do |connection|
connection.execute(query)
end
end
end
def result
@thread.value
end
end
count = ActiveRecord::Base.connection_pool.instance_variable_get(:@size) * 2
puts "#{count} queries"
Benchmark.bm do |x|
query = 'SELECT sleep(1)'
x.report('sync:') do
count.times do
ActiveRecord::Base.connection.execute(query)
end
end
x.report('conc:') do
futures = []
count.times do
futures << DeferredQuery.new(query)
end
futures.each {|q| q.result }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment