shell执行命令数

时间:2013-07-28 04:52:29

标签: ruby

我需要执行一组这样的命令:

system("command1; command2; command3")
如果我像上面那样做而不是做

,那么在速度或任何其他指标方面是否有任何优势
system "command1"
system "command2"
system "command3"

2 个答案:

答案 0 :(得分:2)

可能Ruby执行比shell脚本慢,所以在shell中将序列扩展为三个命令比在Ruby中执行要快。

但速度差异可能很小。更重要的是,这三个命令中的每一个在Ruby代码中是否具有逻辑意义。如果它们被认为是一个从未在Ruby代码中的逻辑级别内分离的块,那么在shell中连接它们更有意义。如果每个命令确实对应于Ruby代码中的某些逻辑概念,那么将它们分开就更有意义了。

基准

t = Time.now
100.times do
  system("echo foo; ls; echo bar ")
end
t1 = Time.now - t

t = Time.now
100.times do
  system("echo foo ")
  system("ls ")
  system("echo bar ")
end
t2 = Time.now - t

puts "Together: #{t1}", "Separate: #{t2}"

结果

Together: 0.673181442
Separate: 1.177105366

答案 1 :(得分:1)

除了@ sawa的答案之外,还有spawn,它不会等待进程在开始下一个进程之前结束。它更快:

n = 100
t = Time.now
n.times do
  system("echo foo; ls; echo bar ")
end
t1 = Time.now - t

t = Time.now
n.times do
  system("echo foo ")
  system("ls ")
  system("echo bar ")
end
t2 = Time.now - t

t = Time.now
n.times do
  spawn("echo foo ")
  spawn("ls ")
  spawn("echo bar ")
end
t3 = Time.now - t

t = Time.now
n.times do
  spawn("echo foo; ls; echo bar ")
end
t4 = Time.now - t

puts "Together: #{t1}", "Separate: #{t2}", "Spawned: #{t3}",, "Spawned together: #{t4}"

输出:

Together: 0.242906748
Separate: 0.379665418
Spawned: 0.1551359
Spawned together: 0.083032541