例如,给定一个列表xs = [1..10]
,我想要的是:
[(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10),(10,1)]
我的解决方法是
zip xs (tail xs ++ [head xs]) -- solution (1)
有人建议
zip xs (tail . cycle $ xs) -- solution (2)
但我不知道解决方案(2)是否更有效?或两个解决方案是等效的?
答案 0 :(得分:1)
我的直觉是它们将具有相同的性能。如果您希望根据经验给出经验性的答案,那么应该为自己建立一个小的基准。条件或timeit包是这里的流行选择。请确保编译并使用-O2
,因为解释器的性能不稳定,GHC的优化器非常聪明。
答案 1 :(得分:1)
出乎意料!解决方案(1)更快。我只是使用GHC运行时系统统计信息对其进行测试。测试用例是[1..10^7]
,下面是代码:
解决方案(1):
xs = [1..10^7]
main = print $ last $ zip xs (tail xs ++ [head xs])
解决方案(2):
xs = [1..10^7]
main = print $ last $ zip xs (tail . cycle $ xs )
编译选项:
ghc -O2 -rtsopts ZipCycleList1.hs
运行选项:
ZipCycleList1.exe +RTS -s
解决方案(1)的结果:
1,520,081,768 bytes allocated in the heap
603,912 bytes copied during GC
42,960 bytes maximum residency (2 sample(s))
26,672 bytes maximum slop
2 MB total memory in use (0 MB lost due to fragmentation)
Tot time (elapsed) Avg pause Max pause
Gen 0 1459 colls, 0 par 0.000s 0.004s 0.0000s 0.0006s
Gen 1 2 colls, 0 par 0.000s 0.000s 0.0001s 0.0002s
INIT time 0.000s ( 0.001s elapsed)
MUT time 0.312s ( 0.305s elapsed)
GC time 0.000s ( 0.004s elapsed)
EXIT time 0.000s ( 0.000s elapsed)
Total time 0.312s ( 0.310s elapsed)
%GC time 0.0% (1.3% elapsed)
Alloc rate 4,872,025,717 bytes per MUT second
Productivity 100.0% of total user, 98.5% of total elapsed
解决方法(2):
1,520,081,832 bytes allocated in the heap
992,426,304 bytes copied during GC
250,935,040 bytes maximum residency (12 sample(s))
42,981,632 bytes maximum slop
569 MB total memory in use (0 MB lost due to fragmentation)
Tot time (elapsed) Avg pause Max pause
Gen 0 1449 colls, 0 par 0.296s 0.301s 0.0002s 0.0006s
Gen 1 12 colls, 0 par 0.406s 0.622s 0.0518s 0.2284s
INIT time 0.000s ( 0.001s elapsed)
MUT time 0.328s ( 0.305s elapsed)
GC time 0.702s ( 0.922s elapsed)
EXIT time 0.000s ( 0.000s elapsed)
Total time 1.030s ( 1.228s elapsed)
%GC time 68.2% (75.1% elapsed)
Alloc rate 4,640,024,688 bytes per MUT second
Productivity 31.8% of total user, 24.9% of total elapsed