2011-06-17 25 views
5

因爲我做了一段時間測量的那一刻,我想知道,如果它可以測量用戶時間和系統時間不使用Benchmark類或命令行實用程序time衡量用戶時間和系統時間不基準或時間

使用Time類只顯示掛鐘時間,而不是系統和用戶時間,但是我正在尋找具有相同靈活性的解決方案,例如,

time = TimeUtility.now 
# some code 
user, system, real = TimeUtility.now - time 

的原因是,我不喜歡莫名其妙Benchmark,因爲它不能返回數據只(編輯:我錯了 - 它可以看到下面的答案。)。當然,我可以解析輸出結果,但這不正確。從* NIX系統的time工具應該解決我的問題爲好,但我想知道是否已經有某種包裝的Ruby實現,所以我不需要由我自己做出這些系統調用。

非常感謝!

回答

8

我重讀基準文檔,發現它有一個名爲measure方法。這種方法不正是我想要的東西:測量你的代碼所需要的時間和返回包含用戶時間的對象,系統時間,兒童等的系統時間,它是那麼容易,因爲

require 'benchmark' 
measurement = Benchmark.measure do 
    # your code goes here 
end 

在這個過程中,我發現您可以將自定義行添加到Benchmark輸出。你可以用它來獲得兩全其美(自定義時間的測量,並在年底一個不錯的輸出)如下:

require 'benchmark' 

measurements = [] 
10.times { measurements << Benchmark.measure { 1_000_000.times { a = "1" } } } 

# measurements.sum or measurements.inject(0){...} does not work, since the 
# array contains Benchmark instances, which cannot be coerced into Fixnum's 
# Array#sum will work if you are using Rails 
sum = measurements.inject(nil) { |sum, t| sum.nil? ? sum = t : sum += t } 
avg = sum/measurements.size 

# 7 is the width reserved for the description "sum:" and "avg:" 
Benchmark.bm(7, "sum:", "avg:") do |b| 
    [sum, avg] 
end 

結果將如下所示:

   user  system  total  real 
sum:  2.700000 0.000000 2.700000 ( 2.706234) 
avg:  0.270000 0.000000 0.270000 ( 0.270623) 
+0

我只希望有'require'基準測試的快捷方式; Benchmark.measure {...}' – dolzenko 2013-12-25 18:57:38

+0

我不明白,引用的部分很短。你想要點什麼? (Pseduo代碼允許;) – 2013-12-28 23:23:46

+0

當然,可能不會比這更短,只是感嘆缺乏一些默認提供的快捷鍵以保存輸入。 +我總是忘記它是'measure'還是'bm'或'bmbm'或其他東西:) – dolzenko 2013-12-30 13:47:13

2

您可以使用Process::times函數,它返回用戶的時間/系統時間。 (它不報告掛鐘時間,你需要其他的東西)。似乎是一個版本或操作系統依賴,但。

這是它在我的系統(Linux操作系統,紅寶石1.8.7)上報道:

$ irb 
irb(main):001:0> t = Process.times 
=> #<struct Struct::Tms utime=0.01, stime=0.0, cutime=0.0, cstime=0.0> 

該文檔顯示這個雖然如此,一些版本/實現可能只有前兩個:

t = Process.times 
[ t.utime, t.stime ] #=> [0.0, 0.02] 

在Linux上的基本呼叫請參閱times

這裏是一個非常糟糕的包裝形式的支持-

class SysTimes 

    attr_accessor :user, :system 

    def initialize 
     times = Process.times 
     @user = times.utime 
     @system = times.stime 
    end 

    def -(other) 
     diff = SysTimes.new 
     diff.user = @user - other.user 
     diff.system = @system - other.system 
     diff 
    end 
end 

應該給你的想法,使其在你的情況下很好地工作。

+0

可悲的是它不知道如何來回應'一個struct -',從而'時間= Process.times; user,system = Process.times - time'會引發錯誤。然而,之前並不知道這種方法,我喜歡這種方法,因爲我可能會查看我的程序在任何時間點運行了多久。 :)感謝您的貢獻! – 2011-06-17 05:59:27

0

這種寶石可能有幫助: https://github.com/igorkasyanchuk/benchmark_methods

沒有更多這樣的代碼:

t = Time.now 
user.calculate_report 
puts Time.now - t 

現在,你可以這樣做:

benchmark :calculate_report # in class 

並調用你的方法

user.calculate_report