Add block vs ensure benchmark

This commit is contained in:
Loic Nageleisen 2023-04-12 15:34:36 +02:00
commit 484269dba2
Signed by: lloeki
GPG key ID: D05DAEE6889F94C2
4 changed files with 80 additions and 0 deletions

29
block-ensure/example.rb Executable file
View file

@ -0,0 +1,29 @@
#!/usr/bin/env ruby
require 'benchmark'
class Example
def initialize
@mutex = Mutex.new
end
def using_block
@mutex.synchronize do
end
end
def using_ensure
@mutex.lock
ensure
@mutex.unlock
end
end
Benchmark.bm(12) do |x|
ex = Example.new
n = 10_000_000
x.report('block') { n.times { ex.using_block } }
x.report('ensure') { n.times { ex.using_ensure } }
end