Skip to content

Instantly share code, notes, and snippets.

@jballanc
Forked from ahoward/a.rb
Created August 19, 2012 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jballanc/3397719 to your computer and use it in GitHub Desktop.
Save jballanc/3397719 to your computer and use it in GitHub Desktop.
threads are so dang awesome
strategy =
String(ARGV.shift || 'thread')
n =
Integer(ARGV.shift || 4)
mb =
2 ** 20
a = b =
nil
size =
0
case strategy
when /THREAD/i
threads = []
q = Queue.new
a = Time.now.to_f
n.times do
threads << Thread.new do
Leak!(mb)
q.push Thread.current.object_id
sleep
end
end
n.times do
q.pop
end
b = Time.now.to_f
size = Process.rsize
when /FORK/i
pids = []
a = Time.now.to_f
n.times do
r, w = IO.pipe
if pid = fork
pids << pid
w.close
_size = Integer(r.read.strip)
size += _size
else
r.close
Leak!(mb)
w.puts(Process.rsize)
w.close
sleep
end
end
b = Time.now.to_f
size += Process.rsize
when /GCD/i
q = Queue.new
a = Time.now.to_f
n.times do
Dispatch::Queue.concurrent.async do
Leak!(mb)
q.push Thread.current.object_id
sleep
end
end
n.times do
q.pop
end
b = Time.now.to_f
size = Process.rsize
end
y(
:n => (n),
:elapsed => (b - a),
:size => ('%2.2fmb' % (size / mb.to_f))
)
BEGIN {
require 'thread'
require 'yaml'
def y o
puts o.to_yaml
end
def Leak! n
Array.new(n){|i| i * rand}
end
module Process
def self.size pid = Process.pid
stdout = `ps wwwux -p #{ pid }`.split(%r/\n/)
vsize, rsize = stdout.last.split(%r/\s+/)[4,2].map{|i| i.to_i * 1024}
end
def self.vsize
size.first
end
def self.rsize
size.last
end
end
}
__END__
Earth: ~/Desktop > ruby --version
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.4.0]
Earth: ~/Desktop > ruby a.rb thread 10
---
:n: 10
:elapsed: 4.798428058624268
:size: 515.40mb
Earth: ~/Desktop > ruby a.rb fork 10
---
:n: 10
:elapsed: 4.163248777389526
:size: 607.65mb
Earth: ~/Desktop > macruby --version
MacRuby 0.13 (ruby 1.9.2) [universal-darwin11.0, x86_64]
Earth: ~/Desktop > macruby a.rb thread 10
---
:n: 10
:elapsed: 0.59968376159668
:size: 98.39mb
Earth: ~/Desktop > macruby a.rb gcd 10
---
:n: 10
:elapsed: 0.574393272399902
:size: 99.21mb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment