我正在编写一个Ruby 1.9.2脚本来评估不同外部命令行调用的执行时间。
我使用ruby Process.system方法执行命令行调用,并尝试按如下方式捕获执行时间:
start = Time.now
system("./script1", "argX")
puts "Duration: #{Time.now - start} seconds"
现在我遇到的问题是持续时间并不反映外部进程的执行时间,而是“系统”调用的执行时间。
知道如何衡量外部流程的执行时间吗?
答案 0 :(得分:12)
好。如果我理解你想要做什么,你想要计算“./script1”调用运行多长时间?
您可能想要做的一件事是使用benchmark库(它是标准的)。
require 'benchmark'
Benchmark.bm (7) do |x|
x.report ("script1:") {system("./script1", "argX")}
end
这将生成一个包含用户和系统时间的报告,这可能是您想要的。
答案 1 :(得分:3)
您可以使用time
并解析结果
require 'open3'
command = './script1 argX'
stdout,stderr,status = Open3.capture3("time #{command}")
results = {}
stderr.split("\n").each do |line|
unless line.blank?
result_type,result = line.split("\t")
results[result_type] = result
end
end
puts "Clock time was #{results['real']}"
time
输出类似
real 0m0.003s
user 0m0.001s
sys 0m0.002s
并将其输出到标准错误,这就是为什么我们需要使用Open3
来获取它(并将其与脚本的输出区分开来,这有希望不会与time
的输出发生冲突。
请注意,time已经过了一段时间的“格式化”输出,因此您可能需要进行一些解析才能将其转换为原始毫秒格式。
答案 2 :(得分:2)
如果我理解正确,您需要为执行脚本的Ruby进程计时。当您使用* nix系统时,您可以使用time
实用程序。然后,您可以执行以下操作:time ruby *yourscript*