Please advise us of other âhelpful hintsâ that should go here!
11.1. Sooner: producing a program more quickly¶-O
or (especially) -O2
:
By using them, you are telling GHC that you are willing to suffer longer compilation times for better-quality code.
GHC is surprisingly zippy for normal compilations without -O
!
Within reason, more memory for heap space means less garbage collection for GHC, which means less compilation time. If you use the -Rghc-timing
option, youâll get a garbage-collector report. (Again, you can use the cheap-and-nasty +RTS -S -RTS
option to send the GC stats straight to standard error.)
If it says youâre using more than 20% of total time in garbage collecting, then more memory might help: use the -Hâ¨sizeâ©
(see -H [â¨sizeâ©]
) option. Increasing the default allocation area size used by the compilerâs RTS might also help: use the +RTS -Aâ¨sizeâ© -RTS
option (see -A â¨sizeâ©
).
If GHC persists in being a bad memory citizen, please report it as a bug.
As soon as GHC plus its âfellow citizensâ (other processes on your machine) start using more than the real memory on your machine, and the machine starts âthrashing,â the party is over. Compile times will be worse than terrible! Use something like the csh builtin time command to get a report on how many page faults youâre getting.
If you donât know what virtual memory, thrashing, and page faults are, or you donât know the memory configuration of your machine, donât try to be clever about memory use: youâll just make your life a misery (and for other people, too, probably).
Because Haskell objects and libraries tend to be large, it can take many real seconds to slurp the bits to/from a remote filesystem.
It would be quite sensible to compile on a fast machine using remotely-mounted disks; then link on a slow machine that had your disks directly mounted.
Read
unnecessarily:
Itâs ugly and slow.
Weâd rather you reported such behaviour as a bug, so that we can try to correct it.
To figure out which part of the compiler is badly behaved, the -v2
option is your friend.
The key tool to use in making your Haskell program run faster are GHCâs profiling facilities, described separately in Profiling. There is no substitute for finding where your programâs time/space is really going, as opposed to where you imagine it is going.
Another point to bear in mind: By far the best way to improve a programâs performance dramatically is to use better algorithms. Once profiling has thrown the spotlight on the guilty time-consumer(s), it may be better to re-think your program than to try all the tweaks listed below.
Another extremely efficient way to make your program snappy is to use library code that has been Seriously Tuned By Someone Else. You might be able to write a better quicksort than the one in Data.List
, but it will take you much longer than typing import Data.List
.
Please report any overly-slow GHC-compiled programs. Since GHC doesnât have any credible competition in the performance department these days itâs hard to say what overly-slow means, so just use your judgement! Of course, if a GHC compiled program runs slower than the same program compiled with NHC or Hugs, then itâs definitely a bug.
-O
or -O2
:
This is the most basic way to make your program go faster. Compilation time will be slower, especially with -O2
.
At present, -O2
is nearly indistinguishable from -O
.
The LLVM code generator can sometimes do a far better job at producing fast code than the native code generator. This is not universal and depends on the code. Numeric heavy code seems to show the best improvement when compiled via LLVM. You can also experiment with passing specific flags to LLVM with the -optlo â¨optionâ©
and -optlc â¨optionâ©
flags. Be careful though as setting these flags stops GHC from setting its usual flags for the LLVM optimiser and compiler.
Haskellâs overloading (using type classes) is elegant, neat, etc., etc., but it is death to performance if left to linger in an inner loop. How can you squash it?
Signatures are the basic trick; putting them on exported, top-level functions is good software-engineering practice, anyway. (Tip: using the -Wmissing-signatures
option can help enforce good signature-practice).
The automatic specialisation of overloaded functions (with -O
) should take care of overloaded local and/or unexported functions.
SPECIALIZE
pragmas:
Specialize the overloading on key functions in your program. See SPECIALIZE pragma and SPECIALIZE instance pragma.
A low-tech way: grep (search) your interface files for overloaded type signatures. You can view interface files using the --show-iface â¨fileâ©
option (see Other options related to interface files).
$ ghc --show-iface Foo.hi | grep -E '^[a-z].*::.*=>'
And, among other things, lazy pattern-matching is your enemy.
(If you donât know what a âstrict functionâ is, please consult a functional-programming textbook. A sentence or two of explanation here probably would not do much good.)
Consider these two code fragments:
f (Wibble x y) = ... # strict f arg = let { (Wibble x y) = arg } in ... # lazy
The former will result in far better code.
A less contrived example shows the use of BangPatterns
on lets
to get stricter code (a good thing):
f (Wibble x y) = let !(a1, b1, c1) = unpackFoo x !(a2, b2, c2) = unpackFoo y in ...
Itâs all the better if a function is strict in a single-constructor type (a type with only one data-constructor; for example, tuples are single-constructor types).
If your datatype has a single constructor with a single field, use a newtype
declaration instead of a data
declaration. The newtype
will be optimised away in most cases.
Donât guessâlook it up.
Look for your function in the interface file, then for the third field in the pragma; it should say Strictness: â¨stringâ©
. The â¨stringâ© gives the strictness of the functionâs arguments: see the GHC Commentary for a description of the strictness notation.
For an âunpackableâ U(...)
argument, the info inside tells the strictness of its components. So, if the argument is a pair, and it says U(AU(LSS))
, that means âthe first component of the pair isnât used; the second component is itself unpackable, with three components (lazy in the first, strict in the second \& third).â
If the function isnât exported, just compile with the extra flag -ddump-simpl
; next to the signature for any binder, it will print the self-same pragmatic information as would be put in an interface file. (Besides, Core syntax is fun to look at!)
INLINE
d (esp. monads):
Placing INLINE
pragmas on certain functions that are used a lot can have a dramatic effect. See INLINE pragma.
export
list:
If you do not have an explicit export list in a module, GHC must assume that everything in that module will be exported. This has various pessimising effects. For example, if a bit of code is actually unused (perhaps because of unfolding effects), GHC will not be able to throw it away, because it is exported and some other module may be relying on its existence.
GHC can be quite a bit more aggressive with pieces of code if it knows they are not exported.
(The form in which GHC manipulates your code.) Just run your compilation with -ddump-simpl
(donât forget the -O
).
If profiling has pointed the finger at particular functions, look at their Core code. lets
are bad, cases
are good, dictionaries (d.â¨Classâ©.â¨Uniqueâ©
) [or anything overloading-ish] are bad, nested lambdas are bad, explicit data constructors are good, primitive operations (e.g., ==#
) are good, â¦
Putting a strictness annotation (!
) on a constructor field helps in two ways: it adds strictness to the program, which gives the strictness analyser more to work with, and it might help to reduce space leaks.
It can also help in a third way: when used with -funbox-strict-fields
(see -f*: platform-independent flags), a strict field can be unpacked or unboxed in the constructor, and one or more levels of indirection may be removed. Unpacking only happens for single-constructor datatypes (Int
is a good candidate, for example).
Using -funbox-strict-fields
is only really a good idea in conjunction with -O
, because otherwise the extra packing and unpacking wonât be optimised away. In fact, it is possible that -funbox-strict-fields
may worsen performance even with -O
, but this is unlikely (let us know if it happens to you).
When you are really desperate for speed, and you want to get right down to the âraw bits.â Please see Unboxed types for some information about using unboxed types.
Before resorting to explicit unboxed types, try using strict constructor fields and -funbox-strict-fields
first (see above). That way, your code stays portable.
foreign import
(a GHC extension) to plug into fast libraries:
This may take real work, but⦠There exist piles of massively-tuned library code, and the best thing is not to compete with it, but link with it.
Foreign function interface (FFI) describes the foreign function interface.
UArray
)
GHC supports arrays of unboxed elements, for several basic arithmetic element types including Int
and Char
: see the Data.Array.Unboxed library for details. These arrays are likely to be much faster than using standard Haskell 98 arrays from the Data.Array library.
If your programâs GC stats (-S [â¨fileâ©]
RTS option) indicate that itâs doing lots of garbage-collection (say, more than 20% of execution time), more memory might help â with the -H [â¨sizeâ©]
or -A â¨sizeâ©
RTS options (see RTS options to control the garbage collector). As a rule of thumb, try setting -H [â¨sizeâ©]
to the amount of memory youâre willing to let your process consume, or perhaps try passing -H [â¨sizeâ©]
without any argument to let GHC calculate a value based on the amount of live data.
The GHC.Compact module provides a way to make garbage collection more efficient for long-lived data structures. Compacting a data structure collects the objects together in memory, where they are treated as a single object by the garbage collector and not traversed individually.
Decrease the âgo-for-itâ threshold for unfolding smallish expressions. Give a -funfolding-use-threshold=0
option for the extreme case. (âOnly unfoldings with zero cost should proceed.â) Warning: except in certain specialised cases (like Happy parsers) this is likely to actually increase the size of your program, because unfolding generally enables extra simplifying optimisations to be performed.
Avoid Prelude.Read.
Use strip on your executables.
11.4. Thriftier: producing a program that gobbles less heap space¶âI think I have a space leakâ¦â
Re-run your program with +RTS -S
, and remove all doubt! (Youâll see the heap usage get bigger and biggerâ¦) (Hmmm⦠this might be even easier with the -G1
RTS option; so⦠./a.out +RTS -S -G1
)
Once again, the profiling facilities (Profiling) are the basic tool for demystifying the space behaviour of your program.
Strict functions are good for space usage, as they are for time, as discussed in the previous section. Strict functions get right down to business, rather than filling up the heap with closures (the systemâs notes to itself about how to evaluate something, should it eventually be required).
11.5. Controlling inlining via optimisation flags.¶Inlining is one of the major optimizations GHC performs. Partially because inlining often allows other optimizations to be triggered. Sadly this is also a double edged sword. While inlining can often cut through runtime overheads this usually comes at the cost of not just program size, but also compiler performance. In extreme cases making it impossible to compile certain code.
For this reason GHC offers various ways to tune inlining behaviour.
11.5.1. Unfolding creation¶In order for a function from a different module to be inlined GHC requires the functions unfolding. The following flags can be used to control unfolding creation. Making their creation more or less likely:
11.5.2. Inlining decisions¶If a unfolding is available the following flags can impact GHCâs decision about inlining a specific binding.
Should the simplifier run out of ticks because of a inlining loop users are encouraged to try decreasing -funfolding-case-threshold=â¨nâ©
or -funfolding-case-scaling=â¨nâ©
to limit inlining into deeply nested expressions while allowing a higher tick factor.
The defaults of these are tuned such that we donât expect regressions for most user programs. Using a -funfolding-case-threshold=â¨nâ©
of 1-2 with a -funfolding-case-scaling=â¨nâ©
of 15-25 can cause usually small runtime regressions but will prevent most inlining loops from getting out of control.
In extreme cases lowering scaling and threshold further can be useful, but at that point itâs very likely that beneficial inlining is prevented as well resulting in significant runtime regressions.
In such cases itâs recommended to move the problematic piece of code into itâs own module and changing inline parameters for the offending module only.
11.5.3. Inlining generics¶There are also flags specific to the inlining of generics:
11.6. Controlling specialization¶GHC has the ability to optimize polymorphic code for specific type class instances at the use site. We call this specialisation and itâs enabled through -fspecialise
which is enabled by default at -O1 or higher.
GHC does this by creating a copy of the overloaded function, optimizing this copy for a given type class instance. Calls to the overloaded function using a statically known typeclass we created a specialization for will then be replaced by a call to the specialized version of the function.
This can often be crucial to avoid overhead at runtime. However since this involves potentially making many copies of overloaded functions GHC doesnât always apply this optimization by default even in cases where it could do so.
For GHC to be able to specialise, at a miminum the instance it specializes for must be known and the overloaded functions unfolding must be available.
11.6.1. Commonly used flag/pragma combinations¶For applications which arenât very compute heavy the defaults are often good enough as they try to strike a reasonable balance between compile time and runtime.
For libraries, if exported functions would benefit significantly from specialization, itâs recommended to enable -fexpose-overloaded-unfoldings
or manually attach INLINEABLE pragmas to performance relevant functions. This will ensure downstream users can specialize any overloaded functions exposed by the library if itâs beneficial.
If there are key parts of an application which rely on specialization for performance using SPECIALIZE pragmas in combination with either -fexpose-overloaded-unfoldings
or INLINEABLE on key overloaded functions should allow for these functions to specialize without affecting overall compile times too much.
For compute heavy code reliant on elimination of as much overhead as possible itâs recommended to use a combination of -fspecialise-aggressively
and -fexpose-overloaded-unfoldings
or -fexpose-all-unfoldings
. However this comes at a big cost to compile time.
Unfolding availabiliy is primarily determined by these flags.
Of particular interest for specialization are:
The former making all unfoldings available, potentially at high compile time cost. The later only makes available the functions that are overloaded. Itâs generally better to use -fexpose-overloaded-unfoldings
over -fexpose-all-unfoldings
when the goal is to ensure specializations.
Functions get considered for specialization either implicitly when GHC sees a use of an overloaded function used with concrete typeclass instances or explicitly when a user requests it through pragmas, see SPECIALIZE pragma and SPECIALIZE instance pragma.
The specializer then checks a number of conditions in order to decide weither or not specialization should happen. Below is a best effort of the list of conditions GHC checks currently.
If any of the type class instances have type arguments and -fpolymorphic-specialisation
is not enabled (off by default) the function wonât be specialised, otherwise
if the specialization was requested through a pragma GHC will try to create a specialization, otherwise
if the function is imported and: + if the unfolding is not available the function canât be specialized, otherwise + if -fcross-module-specialise
is not enabled (enabled by -O) the function wonât be specialised, otherwise + if the flag is enabled, and the function has no INLINABLE/INLINE pragma it wonât be specialised, otherwise
if -fspecialise-aggressively
is enabled GHC will try to create a specialization, otherwise
if the overloaded function is defined in the current module, and all type class instances are statically known it will be specialized, otherwise
the function wonât be specialized.
Note that there are some cases in which GHC will try to specialize a function and fail. For example if a functions has an OPAQUE pragma or the unfolding is not available.
Once a function is specialized GHC will create a rule, similar to these created by RULE pragmas which will fire at call sites involving known instances, replacing calls to the overloaded function with calls to the specialized function when possible.
11.7. Understanding how OS memory usage corresponds to live data¶A confusing aspect about the RTS is the sometimes big difference between OS reported memory usage and the amount of live data reported by heap profiling or GHC.Stats
.
There are two main factors which determine OS memory usage.
Firstly the collection strategy used by the oldest generation. By default a copying strategy is used which requires at least 2 times the amount of currently live data in order to perform a major collection. For example, if your programâs live data is 1G then you would expect the OS to report at minimum 2G.
If instead you are using the compacting (-c
) or nonmoving (-xn
) strategies for the oldest generation then less overhead is required as the strategy immediately reuses already allocated memory by overwriting. For a program with heap size 1G then you might expect the OS to report at minimum a small percentage above 1G.
Secondly, after doing some allocation GHC is quite reluctant to return the memory to the OS. This is because after performing a major collection the program might still be allocating a lot and it costs to have to request more memory. Therefore the RTS keeps an extra amount to reuse which depends on the -F â¨factorâ©
option. By default the RTS will keep up to (2 + F) * live_bytes
after performing a major collection due to exhausting the available heap. The default value is F = 2
so you can see OS memory usage reported to be as high as 4 times the amount used by your program.
Without further intervention, once your program has topped out at this high threshold, no more memory would be returned to the OS so memory usage would always remain at 4 times the live data. If you had a server with 1.5G live data, then if there was a memory spike up to 6G for a short period, then OS reported memory would never dip below 6G. This is what happened before GHC 9.2. In GHC 9.2 memory is gradually returned to the OS so OS memory usage returns closer to the theoretical minimums.
The -Fd â¨factorâ©
option controls the rate at which memory is returned to the OS. On consecutive major collections which are not triggered by heap overflows, a counter (t
) is increased and the F
factor is inversly scaled according to the value of t
and Fd
. The factor is scaled by the equation:
\[\texttt{F}' = \texttt{F} \times {2 ^ \frac{- \texttt{t}}{\texttt{Fd}}}\]
By default Fd = 4
, increasing Fd
decreases the rate memory is returned.
Major collections which are not triggered by heap overflows arise mainly in two ways.
Idle collections (controlled by
-I â¨secondsâ©
)Explicit trigger using
performMajorGC
.
For example, idle collections happen by default after 0.3 seconds of inactivity. If you are running your application and have also set -Iw30
, so that the minimum period between idle GCs is 30 seconds, then say you do a small amount of work every 5 seconds, there will be about 10 idle collections about 5 minutes. This number of consecutive idle collections will scale the F
factor as follows:
\[\texttt{F}' = 2 \times {2^{\frac{-10}{4}}} \approx 0.35\]
and hence we will only retain (0.35 + 2) * live_bytes
rather than the original 4 times. If you want less frequent idle collections then you should also decrease Fd
so that more memory is returned each time a collection takes place.
If you set -Fd0
then GHC will not attempt to return memory, which corresponds with the behaviour from releases prior to 9.2. You probably donât want to do this as unless you have idle periods in your program the behaviour will be similar anyway. If you want to retain a specific amount of memory then itâs better to set -H1G
in order to communicate that you are happy with a heap size of 1G
. If you do this then OS reported memory will never decrease below this amount if it ever reaches this threshold.
The collecting strategy also affects the fragmentation of the heap and hence how easy it is to return memory to a theoretical baseline. Memory is allocated firstly in the unit of megablocks which is then further divided into blocks. Block-level fragmentation is how much unused space within the allocated megablocks there is. In a fragmented heap there will be many megablocks which are only partially full.
In theory the compacting strategy has a lower memory baseline but practically it can be hard to reach the baseline due to how compacting never defragments. On the other hand, the copying collecting has a higher theoretical baseline but we can often get very close to it because the act of copying leads to lower fragmentation.
There are some other flags which affect the amount of retained memory as well. Setting the maximum heap size using -M â¨sizeâ©
will make sure we donât try and retain more memory than the maximum size and explicitly setting -H [â¨sizeâ©]
will mean that we will always try and retain at least H
bytes irrespective of the amount of live data.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4