2010-07-08 33 views
1

我有這個試用計時器代碼在Ruby的時間euler解決方案。在時間上的差異是返回一個負數

$RUNS = 12 
def run(solve) 
    times = [] 
    $RUNS.times do 
    start_t = Time.now.usec 
    solve.call 
    end_t = Time.now.usec 
    times << (end_t - start_t)/1000.0 
    end 
    #times = times.delete_if {|i| i < 0} 
    puts times.inspect 
    times.sort 

    mean = times.inject{|a,c| a+c}/$RUNS 
    puts("Mean:\t#{mean}"); 
    if (times.length % 2 == 0) then 
    median = (times[times.length/2 - 1] + times[times.length/2])/2.0 
    else 
    median = times[times.length/2]; 
    end 
    puts("Median: #{median}"); 

end 

不幸的是,我一直得到的答案是這樣的:

[409.805, 418.16, -582.23, 402.223, -581.94, 413.196, 426.816, -584.732, 519.457, -569.557, 558.918, -579.176] 

我能做些什麼來避免這些奇怪的負數?

回答

2

usec返回的時間與微秒相同爲month返回的月份。它不是自紀元以來的特定時間的微秒數。

因此,如果start_t爲1049896564.259970秒,end_t爲1049896592.123130秒,那麼如果您扣除了usecs,則將得到123130 - 259970。即負數。

相反,您可以使用Time.now.to_f轉換爲自時代以來的浮點數秒,並將它們相減。您也可以直接減去另一個Time對象。

start_t = Time.now 
solve.call 
end_t = Time.now 
times << end_t - start_t 
+0

那麼我該如何在Ruby中進行高粒度時序? – 2010-07-08 23:19:18

+0

@Jbrristow答案更新瞭如何做你想要的建議。 – mikej 2010-07-08 23:25:16

+0

這似乎是要求浮點錯誤,但我乘以1000以獲得毫秒粒度。 – 2010-07-09 00:00:40

0

在自紀元秒當前時間:

Time.now.to_f 
=> 1278631398.143 

這應該有微秒的分辨率,雖然只有三位小數正在這裏顯示。