How to tell that common subexpression elimination is happening or not in GHC?

半腔热情 提交于 2019-12-12 03:33:24

问题


Let's say I have a naively implemented function like this:

quadratic a b c = (ans1, ans2)
  where
    ans1 = ((-b) + sqrt (b * b - 4 * a * c)) / (2 * a)
    ans2 = ((-b) - sqrt (b * b - 4 * a * c)) / (2 * a)

There are multiple identical subexpressions. How can I tell without reading core that common subexpression elimination is happening or not and to which parts of this?


回答1:


Using trace might tell you as demonstrated in this SO question.

import Debug.Trace

quadratic a b c = (ans1, ans2)
  where
    ans1 = ((-b) + tr1 (sqrt (b * b - 4 * a * c))) / (2 * a)
    ans2 = ((-b) - tr2 (sqrt (b * b - 4 * a * c))) / (2 * a)
    tr1 = trace "ans1"
    tr2 = trace "ans2"

main = print $ quadratic 1 10 3

Compiling this with -O2 or -O3 shows both ans1 and ans2 in the trace output indicating that GHC did not perform the CSE. You get similar results if you use tr1 in both places.

The Haskell Wiki mentions that GHC only performs CSE in limited circumstances - (link) - and that you are advised to perform it yourself if you want to make sure it happens.



来源:https://stackoverflow.com/questions/39208877/how-to-tell-that-common-subexpression-elimination-is-happening-or-not-in-ghc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!