/
slides.tex
1705 lines (1384 loc) · 41.1 KB
/
slides.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass{beamer}
\usepackage{listings}
% \usepackage{pgfpages}
% \pgfpagesuselayout{4 on 1}[a4paper,border shrink=5mm,landscape]
\title{High-Performance Haskell}
\author{Johan Tibell\\johan.tibell@gmail.com}
\date{2010-10-01}
\begin{document}
\lstset{language=Haskell}
\frame{\titlepage}
\begin{frame}
\frametitle{Welcome!}
A few things about this tutorial:
\begin{itemize}
\item Stop me and ask questions---early and often
\item I assume \emph{no} prior Haskell exposure
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Sequential performance is still important}
Parallelism is not a magic bullet:
\begin{itemize}
\item The speedup of a program using multiple processors is limited
by the time needed for the sequential fraction of the
program. (Amdahl's law)
\item We want to make \emph{efficient} use of every core.
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Caveats}
The usual caveats about performance optimizations:
\begin{itemize}
\item Improvements to the compiler might make some optimizations
redundant. Write benchmarks to detect these cases.
\item Some optimizations are compiler (i.e. GHC) specific
\end{itemize}
That being said, many of these optimizations have remained valid
over a number of GHC releases.
\end{frame}
\begin{frame}[fragile]
\frametitle{Software prerequisites}
The Haskell Platform:
\begin{itemize}
\item Download installer for Windows, OS X, or Linux here:
\item \url{http://hackage.haskell.org/platform}
\end{itemize}
The Criterion benchmarking library:
\begin{verbatim}
cabal install -f-Chart criterion
\end{verbatim}
\end{frame}
\begin{frame}
\frametitle{Outline}
\begin{itemize}
\item Introduction to Haskell
\item Lazy evaluation
\item Reasoning about space usage
\item Benchmarking
\item Making sense of compiler output
\item Profiling
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Haskell in 10 minutes}
Our first Haskell program sums a list of integers:
\begin{lstlisting}
sum :: [Int] -> Int
sum [] = 0
sum (x:xs) = x + sum xs
main :: IO ()
main = print (sum [1..10000])
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Type signatures}
\begin{definition}
A \alert{type signature} describes the type of a Haskell expression:
\end{definition}
\begin{lstlisting}
sum :: [Int] -> Int
\end{lstlisting}
\begin{itemize}
\item \lstinline!Int! is an integer.
\item \lstinline![a]! is a list of \lstinline!a!s
\begin{itemize}
\item So \lstinline![Int]! is a list of integers
\end{itemize}
\item \lstinline!->! denotes a function.
\item So \lstinline!sum! is a function from a list of integers to an
integer.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Defining a function}
Functions are defined as a series of equations, using
\emph{pattern matching}:
\begin{lstlisting}
sum [] = 0
sum (x:xs) = x + sum xs
\end{lstlisting}
The list is defined recursively as either
\begin{itemize}
\item an empty list, written as \lstinline![]!, or
\item an element \lstinline!x!, followed by a list \lstinline!xs!.
\end{itemize}
[] is pronounced ``nil'' and \lstinline!:! is pronounced ``cons''.
\end{frame}
\begin{frame}[fragile]
\frametitle{Function application}
Function application is indicated by \emph{juxtaposition}:
\begin{lstlisting}
main = print (sum [1..10000])
\end{lstlisting}
\begin{itemize}
\item \lstinline![1..10000]! creates a list of 10,000 integers from
1 to 10,000.
\item We apply the \lstinline!sum! function to the list and then
apply the result to the print function.
\end{itemize}
We say that we \emph{apply} rather then \emph{call} a function:
\begin{itemize}
\item Haskell is a lazy language
\item The result may not be computed immediately
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Compiling and running our program}
Save the program in a file called \lstinline!Sum.hs! and then
compile it using \lstinline!ghc!:
\begin{verbatim}
$ ghc -O --make Sum.hs
[1 of 1] Compiling Main ( Sum.hs, Sum.o )
Linking Sum ...
\end{verbatim}
Now lets run the program
\begin{verbatim}
$ ./Sum
50005000
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Defining our own data types}
Data types have one or more \emph{constructors}, each with zero or
more \emph{arguments} (or \emph{fields}).
\begin{lstlisting}
data Shape = Circle Double
| Rectangle Double Double
\end{lstlisting}
And a function over our data type, again defined using pattern
matching:
\begin{lstlisting}
area :: Shape -> Double
area (Circle r) = r * r * 3.14
area (Rectangle w h) = w * h
\end{lstlisting}
Constructing a value uses the same syntax as pattern matching:
\begin{lstlisting}
area (Rectangle 3.0 5.0)
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Back to our sum function}
Our \lstinline!sum! has a problem. If we increase the size of the
input
\begin{lstlisting}
main = print (sum [1..10000000])
\end{lstlisting}
and run the program again
\begin{verbatim}
$ ghc -O --make Sum.hs
[1 of 1] Compiling Main ( Sum.hs, Sum.o )
Linking Sum ...
$ ./Sum
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Tail recursion}
Our function creates a stack frame for each recursive call,
eventually reaching the predefined stack limit.
\begin{itemize}
\item Must do so as we still need to apply + to the result of the
call.
\end{itemize}
Make sure that the recursive application is the last thing in the
function
\begin{lstlisting}
sum :: [Int] -> Int
sum xs = sum' 0 xs
where
sum' acc [] = acc
sum' acc (x:xs) = sum' (acc + x) xs
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Polymorphic functions}
Many functions follow the same pattern. For example,
\begin{lstlisting}
product :: [Int] -> Int
product xs = product' 1 xs
where
product' acc [] = acc
product' acc (x:xs) = product' (acc * x) xs
\end{lstlisting}
is just like sum except we replace 0 with 1 and + with *. We can
generalize \lstinline!sum! and \lstinline!product! to
\begin{lstlisting}
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
sum = foldl (+) 0
product = foldl (*) 1
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Summing some numbers...} Using our new definition of
\lstinline!sum!, lets sum all number from 1 to 1000000:
\begin{verbatim}
$ ghc -O --make Sum.hs
[1 of 1] Compiling Main ( Sum.hs, Sum.o )
Linking Sum ...
$ ./Sum
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.
\end{verbatim}
What went wrong this time?
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Laziness
\begin{frame}[fragile]
\frametitle{Laziness}
\begin{itemize}
\item Haskell is a lazy language
\item Functions and data constructors don't evaluate their arguments
until they need them
\begin{lstlisting}
cond :: Bool -> a -> a -> a
cond True t e = t
cond False t e = e
\end{lstlisting}
\item Same with local definitions
\begin{lstlisting}
abs :: Int -> Int
abs x | x > 0 = x
| otherwise = neg_x
where neg_x = negate x
\end{lstlisting}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Why laziness is important}
\begin{itemize}
\item Laziness supports \emph{modular programming}
\item Programmer-written functions instead of built-in language
constructs
\begin{lstlisting}
(||) :: Bool -> Bool -> Bool
True || _ = True
False || x = x
\end{lstlisting}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Laziness and modularity}
Laziness lets us separate producers and consumers and still get
efficient execution:
\begin{itemize}
\item Generate all solutions (a huge tree structure)
\item Find the solution(s) you want
\end{itemize}
\begin{lstlisting}
nextMove :: Board -> Move
nextMove b = selectMove allMoves
where
allMoves = allMovesFrom b
\end{lstlisting}
The solutions are generated as they are consumed.
\end{frame}
\begin{frame}[fragile]
\frametitle{Back to our misbehaving function}
How does evaluation of this expression proceed?
\begin{lstlisting}
sum [1,2,3]
\end{lstlisting}
Like this:
\begin{verbatim}
sum [1,2,3]
==> foldl (+) 0 [1,2,3]
==> foldl (+) (0+1) [2,3]
==> foldl (+) ((0+1)+2) [3]
==> foldl (+) (((0+1)+2)+3) []
==> ((0+1)+2)+3
==> (1+2)+3
==> 3+3
==> 6
\end{verbatim}
\end{frame}
\begin{frame}
\frametitle{Thunks}
A \emph{thunk} represents an unevaluated expression.
\begin{itemize}
\item GHC needs to store all the unevaluated \lstinline!+! expressions
on the heap, until their value is needed.
\item Storing and evaluating thunks is costly, and unnecessary if the
expression was going to be evaluated anyway.
\item \lstinline!foldl! allocates \emph{n} thunks, one for each
addition, causing a stack overflow when GHC tries to evaluate the
chain of thunks.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Controlling evaluation order}
The \lstinline!seq! function allows to control evaluation order.
\begin{lstlisting}
seq :: a -> b -> b
\end{lstlisting}
Informally, when evaluated, the expression \lstinline!seq a b!
evaluates \lstinline!a! and then returns \lstinline!b!.
\end{frame}
\begin{frame}[fragile]
\frametitle{Weak head normal form}
Evaluation stops as soon as a data constructor (or lambda) is
reached:
\begin{verbatim}
ghci> seq (1 `div` 0) 2
*** Exception: divide by zero
ghci> seq ((1 `div` 0), 3) 2
2
\end{verbatim}
We say that \lstinline!seq! evaluates to \emph{weak head normal
form} (WHNF).
\end{frame}
\begin{frame}[fragile]
\frametitle{Weak head normal form}
Forcing the evaluation of an expression using \lstinline!seq! only
makes sense if the result of that expression is used later:
\begin{lstlisting}
let x = 1 + 2 in seq x (f x)
\end{lstlisting}
The expression
\begin{lstlisting}
print (seq (1 + 2) 3)
\end{lstlisting}
doesn't make sense as the result of \lstinline!1+2! is never used.
\end{frame}
\begin{frame}[fragile]
\frametitle{Exercise}
Rewrite the expression
\begin{lstlisting}
(1 + 2, 'a')
\end{lstlisting}
so that the component of the pair is evaluated before the pair is
created.
\end{frame}
\begin{frame}[fragile]
\frametitle{Solution}
Rewrite the expression as
\begin{lstlisting}
let x = 1 + 2 in seq x (x, 'a')
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{A strict left fold}
We want to evaluate the expression \lstinline!f z x! \emph{before}
evaluating the recursive call:
\begin{lstlisting}
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' f z [] = z
foldl' f z (x:xs) = let z' = f z x
in seq z' (foldl' f z' xs)
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Summing numbers, attempt 2}
How does evaluation of this expression proceed?
\begin{verbatim}
foldl' (+) 0 [1,2,3]
\end{verbatim}
Like this:
\begin{verbatim}
foldl' (+) 0 [1,2,3]
==> foldl' (+) 1 [2,3]
==> foldl' (+) 3 [3]
==> foldl' (+) 6 []
==> 6
\end{verbatim}
Sanity check:
\begin{verbatim}
ghci> print (foldl' (+) 0 [1..1000000])
500000500000
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Computing the mean}
A function that computes the mean of a list of numbers:
\begin{lstlisting}
mean :: [Double] -> Double
mean xs = s / fromIntegral l
where
(s, l) = foldl' step (0, 0) xs
step (s, l) a = (s+a, l+1)
\end{lstlisting}
We compute the length of the list and the sum of the numbers in one
pass.
\begin{verbatim}
$ ./Mean
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.
\end{verbatim}
Didn't we just fix that problem?!?
\end{frame}
\begin{frame}[fragile]
\frametitle{seq and data constructors}
Remember:
\begin{itemize}
\item Data constructors don't evaluate their arguments when
created
\item \lstinline!seq! only evaluates to the outmost data
constructor, but doesn't evaluate its arguments
\end{itemize}
Problem: \lstinline!foldl'! forces the evaluation of the pair
constructor, but not its arguments, causing unevaluated thunks build
up inside the pair:
\begin{verbatim}
(0.0 + 1.0 + 2.0 + 3.0, 0 + 1 + 1 + 1)
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Forcing evaluation of constructor arguments}
We can force GHC to evaluate the constructor arguments before the
constructor is created:
\begin{lstlisting}
mean :: [Double] -> Double
mean xs = s / fromIntegral l
where
(s, l) = foldl' step (0, 0) xs
step (s, l) a = let s' = s + a
l' = l + 1
in seq s' (seq l' (s', l'))
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Bang patterns}
A \emph{bang patterns} is a concise way to express that an argument
should be evaluated.
\begin{lstlisting}
{-# LANGUAGE BangPatterns #-}
mean :: [Double] -> Double
mean xs = s / fromIntegral l
where
(s, l) = foldl' step (0, 0) xs
step (!s, !l) a = (s + a, l + 1)
\end{lstlisting}
\lstinline!s! and \lstinline!l! are evaluated before the right-hand
side of \lstinline!step! is evaluated.
\end{frame}
\begin{frame}[fragile]
\frametitle{Strictness}
We say that a function is \emph{strict} in an argument, if
evaluating the function always causes the argument to be evaluated.
\begin{lstlisting}
null :: [a] -> Bool
null [] = True
null _ = False
\end{lstlisting}
\lstinline!null! is strict in its first (and only) argument, as it
needs to be evaluated to pick a return value.
\end{frame}
\begin{frame}[fragile]
\frametitle{Strictness - Example}
\lstinline!cond! is strict in the first argument, but not in the
second and third argument:
\begin{lstlisting}
cond :: Bool -> a -> a -> a
cond True t e = t
cond False t e = e
\end{lstlisting}
Reason: Each of the two branches only evaluate one of the two last
arguments to \lstinline!cond!.
\end{frame}
\begin{frame}[fragile]
\frametitle{Strict data types}
Haskell lets us say that we always want the arguments of a
constructor to be evaluated:
\begin{lstlisting}
data PairS a b = PS !a !b
\end{lstlisting}
When a \lstinline!PairS! is evaluated, its arguments are evaluated.
\end{frame}
\begin{frame}[fragile]
\frametitle{Strict pairs as accumulators}
We can use a strict pair to simplify our \lstinline!mean! function:
\begin{lstlisting}
mean :: [Double] -> Double
mean xs = s / fromIntegral l
where
PS s l = foldl' step (PS 0 0) xs
step (PS s l) a = PS (s + a) (l + 1)
\end{lstlisting}
Tip: Prefer strict data types when laziness is not needed for your
program to work correctly.
\end{frame}
\begin{frame}[fragile]
\frametitle{Reasoning about laziness}
A function application is only evaluated if its result is needed,
therefore:
\begin{itemize}
\item One of the function's right-hand sides will be evaluated.
\item Any expression whose value is required to decide which RHS to
evaluate, must be evaluated.
\end{itemize}
By using this ``backward-to-front'' analysis we can figure which
arguments a function is strict in.
\end{frame}
\begin{frame}[fragile]
\frametitle{Reasoning about laziness: example}
\begin{lstlisting}
max :: Int -> Int -> Int
max x y
| x > y = x
| x < y = y
| otherwise = x -- arbitrary
\end{lstlisting}
\begin{itemize}
\item To pick one of the three RHS, we must evaluate \lstinline!x > y!.
\item Therefore we must evaluate \emph{both} \lstinline!x! and
\lstinline!y!.
\item Therefore \lstinline!max! is strict in both \lstinline!x! and
\lstinline!y!.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Poll}
\begin{lstlisting}
data BST = Leaf | Node Int BST BST
insert :: Int -> BST -> BST
insert x Leaf = Node x Leaf Leaf
insert x (Node x' l r)
| x < x' = Node x' (insert x l) r
| x > x' = Node x' l (insert x r)
| otherwise = Node x l r
\end{lstlisting}
Which arguments is \lstinline!insert! strict in?
\begin{itemize}
\item None
\item 1st
\item 2nd
\item Both
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Solution}
Only the second, as inserting into an empty tree can be done without
comparing the value being inserted. For example, this expression
\begin{lstlisting}
insert (1 `div` 0) Leaf
\end{lstlisting}
does not raise a division-by-zero expression but
\begin{lstlisting}
insert (1 `div` 0) (Node 2 Leaf Leaf)
\end{lstlisting}
does.
\end{frame}
\begin{frame}[fragile]
\frametitle{Some other things worth pointing out}
\begin{itemize}
\item \lstinline!insert x l! is not evaluated before the
\lstinline!Node! is created, so it's stored as a thunk.
\item Most tree based data structures use strict sub-trees:
\begin{lstlisting}
data Set a = Tip
| Bin !Size a !(Set a) !(Set a)
\end{lstlisting}
\end{itemize}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Reasoning about space usage
\begin{frame}[fragile]
\frametitle{Reasoning about space usage}
Knowing how GHC represents values in memory is useful because
\begin{itemize}
\item it allows us to approximate memory usage, and
\item it allows us to count the number of indirections, which affect
cache behavior.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Memory layout}
Here's how GHC represents the list \lstinline![1,2]! in memory:
\begin{figure}
\includegraphics[scale=0.75]{diagrams/list12.pdf}
\end{figure}
\begin{itemize}
\item Each box represents one machine word
\item Arrows represent pointers
\item Each constructor has one word overhead for e.g. GC information
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Memory usage for data constructors}
Rule of thumb: a constructor uses one word for a header, and one
word for each field. So e.g.
\begin{lstlisting}
data Uno = Uno a
data Due = Due a b
\end{lstlisting}
an \lstinline!Uno! takes 2 words, and a \lstinline!Due! takes 3.
\begin{itemize}
\item Exception: a constructor with no fields (like
\lstinline!Nothing! or \lstinline!True!) takes no space, as it's
shared among all uses.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Unboxed types}
GHC defines a number of \emph{unboxed} types. These typically
represent primitive machine types.
\begin{itemize}
\item By convention, the names of these types end with a
\lstinline!#!.
\item Most unboxed types take one word (except
e.g. \lstinline!Double#! on 32-bit machines)
\item Values of unboxed types are never lazy.
\item The basic types are defined in terms unboxed types e.g.
\begin{lstlisting}
data Int = I# Int#
\end{lstlisting}
\item We call types such as \lstinline!Int! \emph{boxed} types
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Poll}
How many machine words is needed to store a value of this data type:
\begin{lstlisting}
data IntPair = IP Int Int
\end{lstlisting}
\begin{itemize}
\item 3?
\item 5?
\item 7?
\item 9?
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{IntPair memory layout}
\begin{figure}
\includegraphics[scale=0.75]{diagrams/intpair.pdf}
\end{figure}
So an \lstinline!IntPair! value takes 7 words.
\end{frame}
\begin{frame}[fragile]
\frametitle{Unpacking}
GHC gives us some control over data representation via the
\lstinline!UNPACK! pragma.
\begin{itemize}
\item The pragma unpacks the contents of a constructor into the
field of another constructor, removing one level of indirection
and one constructor header.
\item Any strict, monomorphic, single-constructor field can be
unpacked.
\end{itemize}
The pragma is added just before the bang pattern:
\begin{lstlisting}
data Foo = Foo {-# UNPACK #-} !SomeType
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Unpacking example}
\begin{lstlisting}
data IntPair = IP Int Int
\end{lstlisting}
\begin{figure}
\includegraphics[scale=0.75]{diagrams/intpair.pdf}
\end{figure}
\begin{lstlisting}
data IntPair = IP {-# UNPACK #-} !Int
{-# UNPACK #-} !Int
\end{lstlisting}
\begin{figure}
\includegraphics[scale=0.75]{diagrams/intpair-unpacked.pdf}
\end{figure}
\end{frame}
\begin{frame}[fragile]
\frametitle{Benefits of unpacking}
When the pragma applies, it offers the following benefits:
\begin{itemize}
\item Reduced memory usage (4 words in the case of
\lstinline!IntPair!)
\item Fewer indirections
\end{itemize}
Caveat: There are cases where unpacking hurts performance e.g. if
the fields are passed to a non-strict function.
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Benchmarking
\begin{frame}[fragile]
\frametitle{Benchmarking}
In principle, measuring code-execution time is trivial:
\begin{enumerate}
\item Record the start time.
\item Execute the code.
\item Record the stop time.
\item Compute the time difference.
\end{enumerate}
\end{frame}
\begin{frame}[fragile]
\frametitle{A naive benchmark}
\begin{verbatim}
import time
def bench(f):
start = time.time()
f()
end = time.time()
print (end - start)
\end{verbatim}
\end{frame}
\begin{frame}
\frametitle{Benchmarking gotchas}
Potential problems with this approach:
\begin{itemize}
\item The clock resolution might be too low.
\item The measurement overhead might skew the results.
\item The compiler might detect that the result of the function
isn't used and remove the call completely!
\item Another process might get scheduled while the benchmark is
running.
\item GC costs might not be completely accounted for.
\item Caches might be warm/cold.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Statistically robust benchmarking}
The Criterion benchmarking library:
\begin{itemize}
\item Figures out how many times to run your function
\item Adjusts for measurement overhead
\item Computes confidence intervals
\item Detects outliers
\item Graphs the results
\end{itemize}
\begin{verbatim}
cabal install -f-Chart Criterion
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Benchmarking our favorite function}
\begin{lstlisting}
import Criterion.Main
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
main = defaultMain [
bench "fib 10" (whnf fib 10)
]
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Benchmark output, part 1}
\begin{verbatim}
$ ./Fibber
warming up
estimating clock resolution...
mean is 8.638120 us (80001 iterations)
found 1375 outliers among 79999 samples (1.7%)
1283 (1.6%) high severe
estimating cost of a clock call...
mean is 152.6399 ns (63 iterations)
found 3 outliers among 63 samples (4.8%)
3 (4.8%) high mild
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Benchmark output, part 2}
\begin{verbatim}
benchmarking fib 10
collecting 100 samples, 9475 iterations each, in
estimated 863.8696 ms
bootstrapping with 100000 resamples
mean: 925.4310 ns, lb 922.1965 ns, ub 930.9341 ns,
ci 0.950
std dev: 21.06324 ns, lb 14.54610 ns, ub 35.05525 ns,
ci 0.950
found 8 outliers among 100 samples (8.0%)
7 (7.0%) high severe
variance introduced by outliers: 0.997%
variance is unaffected by outliers
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\frametitle{Evaluation depth}
\begin{lstlisting}
bench "fib 10" (whnf fib 10)
\end{lstlisting}
\begin{itemize}
\item \lstinline!whnf! evaluates the result to weak head normal form
(i.e. to the outmost data constructor).
\item If the benchmark generates a large data structure (e.g. a
list), you can use \lstinline!nf! instead to force the generation
of the whole data structure.
\item It's important to think about what should get evaluated in the
benchmark to ensure your benchmark reflects the use case you care
about.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Benchmark: creating a list of 10k elements}
\begin{lstlisting}
import Criterion.Main