Skip to content

Instantly share code, notes, and snippets.

@mperham
Last active October 4, 2024 16:25
Show Gist options
  • Save mperham/5cffb51d6eaee6a9b07e17bb0661a69b to your computer and use it in GitHub Desktop.
Save mperham/5cffb51d6eaee6a9b07e17bb0661a69b to your computer and use it in GitHub Desktop.
Atomic counters: MutexFixnum vs concurrent-ruby's AtomicFixnum
require "benchmark/ips"
require "concurrent"
class MutexFixnum
def initialize
@value = 0
@lock = Mutex.new
end
def increment(amount = 1)
@lock.synchronize { @value += amount }
end
def value=(val)
@lock.synchronize {
old = @value
@value = val
old
}
end
end
Benchmark.ips do |x|
[::MutexFixnum, ::Concurrent::AtomicFixnum].each do |klass|
x.report(klass) do |count|
sc = klass.new
count.times { sc.increment }
end
x.report("thread-#{klass}") do |count|
sc = klass.new
t = []
10.times {
t << Thread.new do
count.times { sc.increment }
end
}
t.each(&:join)
end
end
end
jruby 9.4.8.0 (3.1.4) 2024-07-02 4d41e55a67 OpenJDK 64-Bit Server VM 18.0.2.1+0 on 18.0.2.1+0 +jit [arm64-darwin]
Warming up --------------------------------------
MutexFixnum 1.399M i/100ms
thread-MutexFixnum 88.529k i/100ms
Concurrent::AtomicFixnum
8.141M i/100ms
thread-Concurrent::AtomicFixnum
127.454k i/100ms
Calculating -------------------------------------
MutexFixnum 13.902M (± 0.7%) i/s (71.93 ns/i) - 69.965M in 5.032978s
thread-MutexFixnum 823.398k (± 5.3%) i/s (1.21 μs/i) - 4.161M in 5.067168s
Concurrent::AtomicFixnum
79.494M (± 0.9%) i/s (12.58 ns/i) - 398.895M in 5.018339s
thread-Concurrent::AtomicFixnum
1.268M (± 7.6%) i/s (788.80 ns/i) - 6.373M in 5.060407s
ruby 3.3.5 (2024-09-03 revision ef084cc8f4) +YJIT [arm64-darwin23]
Warming up --------------------------------------
MutexFixnum 1.293M i/100ms
thread-MutexFixnum 143.026k i/100ms
Concurrent::AtomicFixnum
1.074M i/100ms
thread-Concurrent::AtomicFixnum
104.075k i/100ms
Calculating -------------------------------------
MutexFixnum 14.924M (± 0.2%) i/s (67.01 ns/i) - 74.970M in 5.023621s
thread-MutexFixnum 1.428M (± 0.8%) i/s (700.32 ns/i) - 7.151M in 5.008456s
Concurrent::AtomicFixnum
10.697M (± 0.4%) i/s (93.49 ns/i) - 53.703M in 5.020592s
thread-Concurrent::AtomicFixnum
1.043M (± 0.9%) i/s (958.88 ns/i) - 5.308M in 5.089994s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment