RubyTapas #147 - #151
147 Atomicity
★
10 x 100のincremental counter
jrubyだと期待通りにならない
lock = Mutex.new ... # in multi threads lock.synchronize do counter += 1 end`
atomic gem
require "atomic" counter = Atomic.new(0) ... counter.update{|c| c + 1}
atomicのperformanceはMRIだと遅いがjrubyだと速い
148 Rake Invoke
★★★
rakeの実行
require "rake" Rake.application.init Rake.application.load_rakefile Rake::Task["hello"].invoke # >> Hello from Rakefile
Rake::Task["hello"].invoke
は2回書いても1度しか走らない
Rake::Task["hello"].execute
なら再実行できる
ruleも実行 Rake::Task["hello.html"].invoke
149 Sum
★★
with Rails (ActiveSupport)
[1,2,3].sum
Without rails -> reduce/inject
sum = data.reduce(0) {|acc, n| acc + n }
add = :+.to_proc add.call(2, 2)
sum = data.reduce(0, &:+) sum = data.reduce(0, :+) sum = data.reduce(:+)
XOR
data = [1,2,3,4,5,6,7,8,9,10] checksum = data.reduce(:^) # => 11
150 Stats
★★
median
sorted = data.sort half_size = sorted.size / 2 middle = if sorted.size.even? sorted[half_size - 1, 2] else sorted[half_size, 1] end med = middle.reduce(:+) / middle.size
sorted = data.sort half_size = sorted.size / 2 q, r = sorted.size.divmod(2) middle = sorted[q - 1 + r, 2 - r] med = middle.reduce(:+) / middle.size
standard deviation
std = Math.sqrt(data.map{|n| (n - avg) ** 2}.reduce(:+) / data.size) std
151 Sleep
★★★
How accurate is #sleep?
MRI
$ ruby test-sleep.rb 0.001 1 Actual length: 1.0832039779999998 seconds Max: 0.002941898 $ ruby test-sleep.rb 0.0001 1 Actual length: 1.5849713390000042 seconds Max: 0.001965845 $ ruby test-sleep.rb 0.00001 1 Min: 1.7454e-05
jruby, rubinius
$ rvm jruby,rbx --verbose do ruby test-sleep.rb 0.001 1 jruby-1.7.4 Actual length: 1.1180506600000006 seconds Max: 0.00272422 rbx-head: rubinius 2.0.0rc1 Actual length: 1.083565672999999 seconds Max: 0.004236704
トータルはRubiniusがMRIに近く正確、Max(外れ値は)jrubyの方が小さい
$ rvm jruby,rbx --verbose do ruby test-sleep.rb 0.0001 1 jruby-1.7.4 Actual length: 0.05607388499999989 seconds Min: 2.002e-06 Max: 0.000120069 rbx-head: rubinius 2.0.0rc1 Actual length: 1.6065821489999945 seconds Min: 0.000108257 Max: 0.00405398
RubiniusはMRIに近い、jrubyは極端に短い値(Actual length)になった