Haskell pauses (apparently) randomly when generating Fibonacci numbers

I played with GHCI and came across this little (me) weirdness.

I tried this:

λ> let fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
λ> fibs

Just to see how fast the fibers are developing, and just play a little. I think it's cool how Haskell displays every Fibo how it is calculated, so this is a good demonstration of laziness.

However, as I saw the wall of numbers approaching, there were instant gaps when the list generation completely stopped. Usually I just think that he calculated the next number, but they seemed to happen randomly - and calculating the next number of chips is always just one addition, so it should never be slow. On one issue, ghci paused for almost a second.

What causes these momentary recessions? Why do they occur only in certain numbers, and not in others? Isn't it always fast?

+4
source share
2 answers

This is almost certainly garbage collection (GC), probably of a higher generation (i.e. the main GC). This can lead to significant pauses in cases where a lot of long-lived garbage is created.

If you want to see this, you can make a quick executable and check:

Start with tmp.hs:

module Main where

fibs = 1:1:zipWith (+) fibs (tail fibs)

main = print $ fibs !! 100000

Compile with ghc -rtsopts tmp.hs

Run with ./tmp +RTS -s

     454,847,088 bytes allocated in the heap
     230,044,816 bytes copied during GC
       4,291,856 bytes maximum residency (226 sample(s))
      18,080,904 bytes maximum slop
              56 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0       676 colls,     0 par    0.07s    0.07s     0.0001s    0.0023s
  Gen  1       226 colls,     0 par    0.27s    0.28s     0.0012s    0.0084s

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time    0.14s  (  0.14s elapsed)
  GC      time    0.34s  (  0.35s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time    0.48s  (  0.49s elapsed)

  %GC     time      71.0%  (71.6% elapsed)

  Alloc rate    3,303,664,644 bytes per MUT second

  Productivity  28.9% of total user, 28.8% of total elapsed

676 226 , 2- ~ 12 , . , , . , GHCI , .

, . , / .

+4

, GC-. (. 4.16.3), , .

, GC, , :

-t [], -s [], -S [], -

, ​​ , , , .. : -t , GHC -Rghc-timing, -s , -S .

+1

All Articles