有誰知道如何讓Haskell代碼更快樂?我在做Project Euler #14。 這段代碼在4.029秒運行:讓Haskell代碼更快更快
collatz :: Int -> Int64 -> Int
collatz c 1 = c
collatz c k
| even k = collatz (c+1) (k `div` 2)
| otherwise = collatz (c+1) (3*k + 1)
main = do
print $ maximum (map (\i -> (collatz 1 i, i)) [1..1000000])
Memoizing的在Collatz功能實際上增加了運行時間,所以我沒有做任何記憶化。 可比C代碼0.239秒運行:
int main(int argc, char *argv[])
{
int maxlength = 0;
int maxstart = 1;
for (int i = 1; i <= 1000000; i++) {
unsigned long k = i;
int length = 1;
while (k > 1) {
length += 1;
if (k % 2 == 0)
k = k/2;
else
k = 3*k + 1;
}
if (length > maxlength) {
maxlength = length;
maxstart = i;
}
}
printf("%d, %d\n", maxlength, maxstart);
return 0;
}
Haskell的代碼被編譯以GHC -O3和C代碼用gcc -std = C99 -O3編譯。
嚴格標註是'shiftR x 1'而不是'div x 2'所遵循的第一件事(是的,一些關鍵優化仍然缺失)。這讓你與C的距離很遠。 – 2014-12-18 23:57:56
這個特殊的歐拉問題在過去產生了大量類似的性能問題。看看[這個搜索](http://stackoverflow.com/search?q= [haskell] + collatz)一堆建議。 [This one](http://stackoverflow.com/questions/13669134/c-vs-haskell-collatz-conjecture-speed-pearison/13669277#13669277)可能特別相關。 – 2014-12-19 00:22:08
你有LLVM嗎?它在-21 -fllvm的機器上運行1.3秒。 – 2014-12-19 00:52:05