剧透警告:这涉及到来自欧拉计划的问题14。
下面的代码需要大约15秒才能运行。我有一个非递归的Java解决方案,只需1秒即可运行。我认为我应该能够将这段代码优化到更接近那个速度。
import Data.List
collatz a 1 = a
collatz a x
| even x = collatz (a + 1) (x `div` 2)
| otherwise = collatz (a + 1) (3 * x + 1)
main = do
print ((foldl1' max) . map (collatz 1) $ [1..1000000])
我使用了+RHS -p
进行了性能分析并发现分配的内存很大,随着输入量的增加而增长。对于n = 100,000
,分配了1GB的内存(!),对于n = 1,000,000
,分配了13GB(!!)的内存。然而,-sstderr
显示尽管分配了大量字节,总内存使用量为1MB,生产率达到95%以上,因此可能13GB是误导性的。
我可以想到一些可能性:
某些部分不够严格。我已经发现了
foldl1'
,但也许我需要做更多的工作?是否有可能将collatz
标记为严格(这种做法是否合理?collatz
没有实现尾递归优化。我认为它应该是这样的,但不知道如何确认。编译器没有执行我认为应该执行的一些优化——例如,
collatz
的只有两个结果需要在任何时候都在内存中(最大值和当前值)
有什么建议吗?
这与Why is this Haskell expression so slow?几乎是重复的,尽管我会指出,快速的Java解决方案不需要执行任何记忆化。有没有办法在不必诉诸记忆化的情况下加快这个程序的运行速度呢?
以下是我的性能分析输出供参考:
Wed Dec 28 09:33 2011 Time and Allocation Profiling Report (Final)
scratch +RTS -p -hc -RTS
total time = 5.12 secs (256 ticks @ 20 ms)
total alloc = 13,229,705,716 bytes (excludes profiling overheads)
COST CENTRE MODULE %time %alloc
collatz Main 99.6 99.4
individual inherited
COST CENTRE MODULE no. entries %time %alloc %time %alloc
MAIN MAIN 1 0 0.0 0.0 100.0 100.0
CAF Main 208 10 0.0 0.0 100.0 100.0
collatz Main 215 1 0.0 0.0 0.0 0.0
main Main 214 1 0.4 0.6 100.0 100.0
collatz Main 216 0 99.6 99.4 99.6 99.4
CAF GHC.IO.Handle.FD 145 2 0.0 0.0 0.0 0.0
CAF System.Posix.Internals 144 1 0.0 0.0 0.0 0.0
CAF GHC.Conc 128 1 0.0 0.0 0.0 0.0
CAF GHC.IO.Handle.Internals 119 1 0.0 0.0 0.0 0.0
CAF GHC.IO.Encoding.Iconv 113 5 0.0 0.0 0.0 0.0
而且,-sstderr:
./scratch +RTS -sstderr
525
21,085,474,908 bytes allocated in the heap
87,799,504 bytes copied during GC
9,420 bytes maximum residency (1 sample(s))
12,824 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 40219 collections, 0 parallel, 0.40s, 0.51s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.00s ( 0.00s elapsed)
MUT time 35.38s ( 36.37s elapsed)
GC time 0.40s ( 0.51s elapsed)
RP time 0.00s ( 0.00s elapsed) PROF time 0.00s ( 0.00s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 35.79s ( 36.88s elapsed) %GC time 1.1% (1.4% elapsed) Alloc rate 595,897,095 bytes per MUT second
Productivity 98.9% of total user, 95.9% of total elapsed
以下是Java解决方案(不是我写的,来自于Project Euler论坛并移除了记忆化):
public class Collatz {
public int getChainLength( int n )
{
long num = n;
int count = 1;
while( num > 1 )
{
num = ( num%2 == 0 ) ? num >> 1 : 3*num+1;
count++;
}
return count;
}
public static void main(String[] args) {
Collatz obj = new Collatz();
long tic = System.currentTimeMillis();
int max = 0, len = 0, index = 0;
for( int i = 3; i < 1000000; i++ )
{
len = obj.getChainLength(i);
if( len > max )
{
max = len;
index = i;
}
}
long toc = System.currentTimeMillis();
System.out.println(toc-tic);
System.out.println( "Index: " + index + ", length = " + max );
}
}