Created
September 15, 2012 15:49
-
-
Save ryoqun/3728542 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def measuring(thread_mode, lock) | |
case thread_mode | |
when :single_threaded | |
yield | |
when :multi_threaded | |
lock.start | |
yield | |
lock.stop | |
else | |
raise "not supported thread mode: #{thread_mode.inspect}" | |
end | |
end | |
def measure(thread_mode, lock) | |
start = Time.now | |
measuring(thread_mode, lock) do | |
100_000.times do | |
lock.lock_and_unlock | |
end | |
end | |
elapsed_time = Time.now - start | |
label = [lock.backend, thread_mode].join(", ") | |
result = format("%-40s: %1.9f seconds", label, elapsed_time) | |
puts(result) | |
end | |
class Lock | |
def start | |
@continue = true | |
@thread = Thread.new do | |
while @continue | |
lock_and_unlock | |
end | |
end | |
end | |
def stop | |
@continue = false | |
@thread.join | |
end | |
def lock_and_unlock | |
lock | |
unlock | |
end | |
end | |
class RubiniusLock < Lock | |
def lock | |
Rubinius.lock(self) | |
end | |
def unlock | |
Rubinius.unlock(self) | |
end | |
def backend | |
'Rubinius.{lock,unlock}' | |
end | |
end | |
class ChannelLock < Lock | |
def initialize | |
@lock = Rubinius::Channel.new | |
@lock.send(nil) | |
end | |
def lock | |
@lock.receive | |
end | |
def unlock | |
@lock.send(nil) | |
end | |
def backend | |
'Channel#{receive,send}' | |
end | |
end | |
5.times do | |
[:single_threaded, :multi_threaded].each do |thread_mode| | |
channel_lock = ChannelLock.new | |
measure(thread_mode, channel_lock) | |
rubinius_lock = RubiniusLock.new | |
measure(thread_mode, rubinius_lock) | |
end | |
puts | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment