2016-03-29 82 views
0

我得到一個讓這段代碼變慢的任務。我可以在方法內改變。原因,爲什麼我這樣做是嘗試ruby分析。如何或在哪裏可以更改代碼以使其更慢?如何減慢代碼的速度

class FibonacciSequence 

    def next_fib 
    @index += 1 

    if @seq[@index].nil? 
     f = @seq[@index - 1] + @seq[@index - 2] 
     @seq[@index] = f 
     return f 
    else 
     return @seq[@index] 
    end 
    end 


    def current_fib 
    return @index >= 0 ? @seq[@index] : nil 
    end 

    def current_index 
    return @index >= 0 ? @index : nil 
    end 


    def [](n) 
    return nil if n < 0 
    return @seq[n] if n <= @index 

    while @index < n 
     self.next_fib 
    end 

    return self.current_fib 
    end 
end 
+5

你可以使用'sleep(num_secs)'延遲執行。 –

+0

是的,我已經試過這個...是否有另一個選項來更改代碼,使其更慢?我有想法給那裏一些循環或一些不必要的行代碼...但我不知道在哪裏和如何。 – user3463055

+0

爲什麼你需要「放慢」你的代碼來分析它?那裏有特定的工具來分析代碼;其中之一是:https://github.com/ruby-prof/ruby-prof – alediaferia

回答

1

sleep(num_secs)是最好的方法。

除此之外,它多次調用函數,通過循環進行循環,使數組/散列表示1000個元素,並應用排序,映射等方法,讀取遠程文件,讀取大量數據並處理它1000用戶名並將它們全部轉換爲大寫,這裏你可以讀取db中的行並更新一些數據並將其保存回去也有幫助,如果你的db是遠程的,這會給你更多的延遲:)

但是睡眠是最好的方法,因爲你可以評論1行,這個代碼將是最優的,或者你可以根據需要更改時間參數。