使用-O2的Haskell编译大大增加内存使用 [英] Haskell compiling with -O2 drastically increases memory usage

查看:156
本文介绍了使用-O2的Haskell编译大大增加内存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的程序在没有ghc的标志编译时运行在不断的内存空间中:

  import Data.List 
fx = x * x
ga = foldl'(+)(fa)[1 ..(1073741824-1)]
main = do putStrLn $ show $ foldl'(+)0 $ map g [0 ,1]

当使用ghc -O2编译时,内存使用量超过系统资源(8GB) / p>

将主要更改为:

  main = do putStrLn $ show $ foldl '(+)0 [g 0,g 1] 

缓解了这个问题,有关地图的说明。



任何人都可以解释这个行为,也许可以解决这个问题吗?



版本是:格拉斯哥Haskell编译器,版本7.4.1,阶段2由GHC版本7.4.1引导

解决方案

这是完整的懒惰优化咬你当它正确运行时,它可以提供运行时间的渐近改进。当它工作错误...这发生。



完整的懒惰变换将常量从绑定移动到封闭的范围。在这种情况下,它正在拾取 [1 ..(1073741824-1)] 常量,并将其移动到封闭的范围。但是,这是完全错误的。它导致它在两个呼叫之间共享,这意味着它不能在第一时间内有效地流式传输。



没有可靠的方式来击败完整的懒惰转换,除了没有-O2的编译。


This simple program runs in constant memory space when compiled with no flags with ghc:

import Data.List
f x = x*x
g a = foldl' (+) (f a) [1..(1073741824-1)]
main = do putStrLn $ show $ foldl' (+) 0 $ map g [0,1]

When compiled with ghc -O2 the memory usage exceeds the system resources (8GB).

Changing main to:

main = do putStrLn $ show $ foldl' (+) 0 [g 0, g 1]

alleviates the problem so it appears to be something to do with the map.

Can anyone explain the behaviour and perhaps how to work around it?

GHC version is: Glasgow Haskell Compiler, Version 7.4.1, stage 2 booted by GHC version 7.4.1

解决方案

This is the full laziness "optimization" biting you. When it works right, it can provide an asymptotic improvement in run time. When it works wrong... This happens.

The full laziness transform moves constants out of bindings to the enclosing scope. In this case, it's picking up on the [1..(1073741824-1)] constant, and moving it to the enclosing scope. However, that's.. completely wrong. It causes it to be shared between the two calls, meaning that it can't stream efficiently the first time.

There is no reliable way to defeat the full laziness transformation, except for compiling without -O2.

这篇关于使用-O2的Haskell编译大大增加内存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆