Skip to content

Instantly share code, notes, and snippets.

@solnic
Last active January 12, 2016 16:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save solnic/338dc444628a8ba4d62c to your computer and use it in GitHub Desktop.
Save solnic/338dc444628a8ba4d62c to your computer and use it in GitHub Desktop.
Validating 10k hashes 1 thread vs 2 (mri, jruby, rbx results)
require 'dry-validation'
require 'active_model'
require 'benchmark'
require 'thread_safe'
schema = Class.new(Dry::Validation::Schema) do
key(:name, &:filled?)
key(:age) { |v| v.int? & v.gt?(18) }
end.new
class User
include ActiveModel::Validations
validates :name, presence: true
validates :age, numericality: { greater_than: 18 }
attr_reader :name, :age
def initialize(attrs)
@name, @age = attrs.values_at(:name, :age)
end
end
count = 10_000
users = count.times.map { |i| { user: "User #{i}", age: 17 } }
Benchmark.bm do |x|
x.report('DV: 1 thread') do
DRY_ST_RESULT = users.map { |user| schema.(user).messages }
end
x.report('AM: 1 thread') do
AM_ST_RESULT = users.map { |user| User.new(user).validate }
end
x.report('DV: 2 threads') do
g1, g2 = users.each_slice(count/2).to_a
DRY_MT_RESULT = ThreadSafe::Array.new
t1 = Thread.new { DRY_MT_RESULT.concat(g1.map { |user| schema.(user).messages }) }
t2 = Thread.new { DRY_MT_RESULT.concat(g2.map { |user| schema.(user).messages }) }
t1.join
t2.join
end
x.report('AM: 2 threads') do
g1, g2 = users.each_slice(count/2).to_a
AM_MT_RESULT = ThreadSafe::Array.new
t1 = Thread.new { AM_MT_RESULT.concat(g1.map { |user| User.new(user).validate }) }
t2 = Thread.new { AM_MT_RESULT.concat(g2.map { |user| User.new(user).validate }) }
t1.join
t2.join
end
end
puts DRY_ST_RESULT.sort == DRY_MT_RESULT.sort
puts AM_ST_RESULT.to_a == AM_MT_RESULT.to_a
user system total real
DV: 1 thread 10.610000 0.170000 10.780000 ( 3.519302)
AM: 1 thread 18.670000 0.240000 18.910000 ( 7.975311)
DV: 2 threads 3.280000 0.050000 3.330000 ( 0.911350)
AM: 2 threads 7.950000 0.090000 8.040000 ( 3.307048)
user system total real
DV: 1 thread 0.960000 0.010000 0.970000 ( 0.977442)
AM: 1 thread 5.810000 0.040000 5.850000 ( 5.897762)
DV: 2 threads 0.990000 0.010000 1.000000 ( 1.005680)
AM: 2 threads 5.720000 0.040000 5.760000 ( 5.786890)
user system total real
DV: 1 thread 9.895571 0.119686 10.015257 ( 5.208915)
AM: 1 thread 28.932377 0.286438 29.218815 ( 15.272448)
DV: 2 threads 7.118843 0.132064 7.250907 ( 3.015258)
AM: 2 threads 20.210797 0.138119 20.348916 ( 7.273697)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment