Skip to content

Instantly share code, notes, and snippets.

@vitalyp
Last active June 24, 2019 15:19
Show Gist options
  • Save vitalyp/f06a9e8483596711920c919c9db610aa to your computer and use it in GitHub Desktop.
Save vitalyp/f06a9e8483596711920c919c9db610aa to your computer and use it in GitHub Desktop.
Draft benchmark code for testing speed of db records updating with commit transaction per each record, and without it
# $ rails c
# > require "#{Rails.root}/test.rb"
# > TestTb.new.test1; TestTb.new.test2
# * Results: 27252 records processed in: 56 sec (within Transaction), 107 sec (without Transaction)
class TestTb
TRANSACTION_SCOPE = -> (func) { Book.transaction { func.call } }
WHERE_QUERY = -> { { autor_id: @value == 0 ? 1 : 0 } }
def initialize; @percent_count = @percents = @count = 0 end
def test1; p 'Single transaction'; call_transactionable(true, 0) end
def test2; p 'Multiple transactions'; call_transactionable(false, 1) end
private
def call_transactionable(transactionable, val)
@value = val
with_init { transactionable ? TRANSACTION_SCOPE.call(self.method(:do_update)) : do_update }
end
def with_init
puts "count = #{@count = Book.where(instance_exec &WHERE_QUERY).count}"
ActiveRecord::Base.logger.silence { puts Benchmark.ms { yield } }
end
def do_update
Book.where(instance_exec &WHERE_QUERY).find_each { |book| update_and_log book }
end
def update_and_log(mv)
mv.update(autor_id: @value)
@percent_count += 1
return if @count/100 != @percent_count
print "\r #{@percents}%"
@percents += 1
@percent_count = 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment