本文介绍了为什么在OS X上的Ruby中,Process.fork会使事情变慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么Process.fork使Ruby中的内容变得这么慢吗?我在OS X El Capitan上使用Ruby 2.3.1.

Can someone explain to me why Process.fork makes stuff so much slower in Ruby? I'm using Ruby 2.3.1 on OS X El Capitan.

require 'time'
require 'benchmark'

def do_stuff
  50000.times { Time.parse(Time.utc(2016).iso8601) }
end

puts Benchmark.measure { do_stuff } # => 1.660000   0.010000   1.670000 (  1.675466)

Process.fork do
  puts Benchmark.measure { do_stuff } # => 3.170000   6.250000   9.420000 (  9.508235)
end

刚注意到,在Linux(经测试的Debian或Ubuntu)上运行该代码不会对性能产生负面影响.

Just noticed that running that code on Linux (tested Debian or Ubuntu) does not result in a negative performance impact.

推荐答案

为什么Process.fork会使OS X上的Ruby中的内容变慢?"

深入了解这一点的第一步是减少变量的数量.

Step one in getting to the bottom of this is to reduce the number of variables.

您运行5万次Time.parse(Time.utc(2016).iso8601)的示例似乎很奇怪.我使用另一个慢速" Ruby任务重新构建了基准测试:

Your example of running Time.parse(Time.utc(2016).iso8601) fifty thousand times seems oddly specific. I reformulated the benchmark test using a different "slow" Ruby task:

require 'benchmark'

def do_stuff
  a = [nil] * 200

  10.times do
    a.each {|x| a.each {|y| a.each {|z| ; }}}; ()
  end
end

puts "main: #{Benchmark.measure { do_stuff }}"

Process.fork do
  puts "fork: #{Benchmark.measure { do_stuff }}"
end

在这里,我已经在大型数组上用无操作嵌套循环替换了Time命令.

Here I've replaced your Time commands with a no-op nested loop over a large array.

结果:

main:   4.020000   0.010000   4.030000 (  4.050664)
fork:   3.940000   0.000000   3.940000 (  3.962207)

main:   3.840000   0.010000   3.850000 (  3.856188)
fork:   3.850000   0.000000   3.850000 (  3.865250)

main:   3.930000   0.000000   3.930000 (  3.937741)
fork:   3.970000   0.000000   3.970000 (  3.986397)

main:   4.340000   0.010000   4.350000 (  4.370009)
fork:   4.300000   0.000000   4.300000 (  4.308156)

没有明显的分叉过程变慢或变快的现象.我已经在OS X和Ubuntu上的Ruby 1.9、2.0和2.3中进行了测试,并且保持不变.

No noticeable pattern of the forked process being slower or faster. I've tested in Ruby 1.9, 2.0, and 2.3 on both OS X and Ubuntu, and it remains the same.

您的问题的答案是:

Process.fork不会使OS X上的Ruby的内容变慢.

Process.fork does not, in general, make stuff slower in Ruby on OS X.

但是,这里还有一个有趣的问题,它是

However, there is a different interesting question here, which is Why is `Time.utc` slower in a forked process in Ruby on OS X (and not in Python)?

这篇关于为什么在OS X上的Ruby中,Process.fork会使事情变慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:26