FakeMutex
Eric Hodel | Wed, 11 Jan 2006 01:23:00 GMT
Adding Mutex makes things slower, but you don’t always need it. For our memcache library I’d like to avoid performing locking when we’re running single-threaded (since that’s what happens most of the time). So, I came up with the idea of FakeMutex that simply yields inside its #synchronize method.
FakeMutex doesn’t give back all the performance of not having locking at all, but it does prevent the code from being messed up with lots of tests to see if we should try to lock or not.
require 'benchmark'
require 'thread'
class FakeMutex
def synchronize
yield
end
end
N = 1_000_000
Benchmark.bmbm do |bm|
fake = FakeMutex.new
real = Mutex.new
bm.report 'NoMutex' do
N.times do
1 + 1
end
end
bm.report 'FakeMutex' do
N.times do
fake.synchronize { 1 + 1 }
end
end
bm.report 'RealMutex' do
N.times do
real.synchronize { 1 + 1 }
end
end
end
Rehearsal ---------------------------------------------
NoMutex 0.870000 0.000000 0.870000 ( 1.004429)
FakeMutex 2.350000 0.020000 2.370000 ( 2.555904)
RealMutex 8.770000 0.030000 8.800000 ( 9.433895)
----------------------------------- total: 12.040000sec
user system total real
NoMutex 0.780000 0.010000 0.790000 ( 0.820284)
FakeMutex 2.350000 0.010000 2.360000 ( 2.536308)
RealMutex 8.780000 0.050000 8.830000 ( 10.722575)
Comments are disabled

Articles