-
-
Save ahoward/3395045 to your computer and use it in GitHub Desktop.
threads are so dang awesome
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
=begin | |
READ THIS FOR CONTEXT: | |
http://tenderlovemaking.com/2012/07/30/is-it-live.html | |
=end | |
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 | |
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__ | |
cfp:~ $ ruby --version | |
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.4.0] | |
cfp:~ $ ruby a.rb thread 4 | |
--- | |
:n: 4 | |
:elapsed: 2.40175199508667 | |
:size: 250.02mb | |
cfp:~ $ ruby a.rb fork 4 | |
--- | |
:n: 4 | |
:elapsed: 1.227113962173462 | |
:size: 246.90mb | |
cfp:~ $ ruby --version | |
jruby 1.6.7.2 (ruby-1.8.7-p357) (2012-05-01 26e08ba) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_33) [darwin-x86_64-java] | |
cfp:~ $ ruby a.rb thread 4 | |
--- | |
:n: 4 | |
:elapsed: 13.164999961853 | |
:size: 186.55mb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wow! https://gist.github.com/3397719
support for leveraging the OS - not replacing it. now if only macruby ran on linux ;-)