Skip to content

Instantly share code, notes, and snippets.

@nominolo
Created May 6, 2014 10:21
Show Gist options
  • Save nominolo/d18efaabf3e074d03969 to your computer and use it in GitHub Desktop.
Save nominolo/d18efaabf3e074d03969 to your computer and use it in GitHub Desktop.
Profiling GHC itself.
-- Use this file to profile GHC itself while compiling a certain file, i.e.,
-- it's equivalent to running something like the following:
--
-- ghc --make <MYTARGET> [<MYFLAG> ...] +RTS -p
--
-- Except that the standard ghc binary doesn't support the RTS option "-p".
-- Note that <MYTARGET> and <MYFLAGS> are hardcoded in the binary. If you
-- change one of these, you need to recompile this binary.
--
--
-- Put into file: ghc-wrap.hs
--
-- $ ghc --make ghc-wrap.hs -prof -fprof-auto -package ghc
--
-- $ ./ghc-wrap +RTS -p # or however you want to run it
--
-- $ less ghc-wrap.prof # or whichever files are generated
--
import GHC
import DynFlags
import System.IO
import GHC.Paths (libdir)
import StaticFlagParser
import Control.Monad
mytarget = "rat.hs" -- Put file you want to compile
myflags = map noLoc ["-prof"] -- The compiler options used to compile the file
main = do
ok <- GHC.defaultErrorHandler (hPutStrLn stderr) defaultFlushOut $ do
(otherflags, _warns1) <- parseStaticFlags myflags
runGhc (Just libdir) $ do
dflags0 <- getSessionDynFlags
(dflags1, leftoverArgs, _warns2)
<- parseDynamicFlagsCmdLine dflags0 otherflags
unless (null leftoverArgs) $
error ("Could not parse flags: " ++ show (map unLoc leftoverArgs))
let dflags2 = dflags1
{ ghcMode = CompManager
, hscTarget = HscAsm
, ghcLink = LinkBinary
}
setSessionDynFlags dflags2
target <- guessTarget mytarget Nothing
setTargets [target]
load LoadAllTargets
print (not (failed ok))
@jberryman
Copy link

Can you point me to any resources about how or why this works? I guess we're using the GHC API and so we're using a good chunk of GHC's internals compiled as a library (with profiling enabled)? Is there any benefit over this to compiling GHC with profiling enabled per https://ghc.haskell.org/trac/ghc/wiki/Debugging/ProfilingGhc ?

@jberryman
Copy link

For ghc 8.0 I had to remove the StaticFlagParser import line, and had to cabal install the ghc-paths package manually

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment