2011-12-14 56 views
2

首先我是Ruby newby,我正在努力學習這門語言。我知道學習的最好方式是真正解決問題。所以我把一個簡單的字符串問題並實現解決方法1這樣的:Ruby 1.9.3多線程實現比單個威脅實現需要更長的時間,爲什麼?

def similarities(str) 
    result = str.length 

    (1..str.length - 1).each { |start| 
    str2 = str[start..-1] 

    index = 0 
    str2.split(//).each do |c| 
     break if c != str[index, 1] 
     index += 1 
    end 

    result += index 
    } 

    result 
end 

然後,它發生,我認爲這是一個「平行的foreach」那種想起絕配。所以,我想出了溶液2

def similarities(str) 
    result = str.length 

    threads = [] 
    (1..str.length - 1).each { |start| 
    str2 = str[start..-1] 
    threads << Thread.new { calculate(str, str2) } 
    } 

    threads.each { |t| t.join; result += t["index"] } 

    result 
end 

def calculate(str, str2) 
    index = 0 
    str2.split(//).each do |c| 
    break if c != str[index, 1] 
    index += 1 
    end 

    Thread.current["index"] = index 
end 

令我驚訝的溶液2了大約8倍以上的時間完全相同的輸入解決方法1運行。爲什麼?

感謝,

回答

3

上下文切換昂貴,遠遠超過你實現實際的,相當瑣碎的計算。如果你想描述這一點,90%的時間可能會被線程相關的系統調用所吞噬。

編輯另外,如果您使用CRuby/MRI,您將受到缺乏真正多線程的限制。詳情請參閱Does ruby have real multithreading?

相關問題