-
Notifications
You must be signed in to change notification settings - Fork 0
/
bench_blog.bs
1124 lines (1022 loc) · 34.1 KB
/
bench_blog.bs
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
<pre class='metadata'>
Title: Error size benchmarking: Redux
Shortname: P1640
Revision: 1
Audience: WG21; DG
Status: P
Group: WG21
URL: https://wg21.link/P1640R1
!Source: <a href="https://github.com/ben-craig/error_bench/blob/master/bench_blog.bs">github.com/ben-craig/error_bench/blob/master/bench_blog.bs</a>
Editor: Ben Craig, National Instruments, ben.craig@gmail.com
Abstract: The author measures size costs of error handling approaches. Exceptions are big, <code>std::abort</code> and integer error codes are small.
Markup Shorthands: markdown yes
</pre>
<script type="text/javascript">
var data_CmpTerm = [
{
type: 'bar',
name: 'throw_exception',
stack: 'throw_exception',
itemStyle: {color: '#9f354d'},
data: [382891,102620,19990,6140]
},
{
type: 'bar',
name: 'baremetal.return_val',
stack: 'return_val',
itemStyle: {color: '#26735a'},
data: [20,14,13,9]
},
{
type: 'bar',
name: 'return_val',
stack: 'return_val',
itemStyle: {color: '#5aad92'},
data: [57404,42746,6373,9]
},
{
type: 'bar',
name: 'abort',
stack: 'abort',
itemStyle: {color: '#FFAE84'},
data: [57376,42732,6360,0]
},
{
type: 'bar',
name: 'noexcept_abort',
stack: 'noexcept_abort',
itemStyle: {color: '#589832'},
barCategoryGap: '10%',
data: [57376,42732,6360,0]
}
];
var data_Cost2ndNeutral = [
{
type: 'bar',
name: 'throw_exception',
stack: 'throw_exception',
itemStyle: {color: '#9f354d'},
data: [140,124,85,105]
},
{
type: 'bar',
name: 'baremetal.return_val',
stack: 'return_val',
itemStyle: {color: '#26735a'},
data: [55,62,68,63]
},
{
type: 'bar',
name: 'return_val',
stack: 'return_val',
itemStyle: {color: '#5aad92'},
data: [135,118,80,63]
},
{
type: 'bar',
name: 'baremetal.abort',
stack: 'abort',
itemStyle: {color: '#ae6039'},
data: [48,48,49,49]
},
{
type: 'bar',
name: 'abort',
stack: 'abort',
itemStyle: {color: '#FFAE84'},
data: [120,104,61,49]
},
{
type: 'bar',
name: 'noexcept_abort',
stack: 'noexcept_abort',
itemStyle: {color: '#589832'},
barCategoryGap: '10%',
data: [120,104,61,49]
}
];
var data_Cost1stError = [
{
type: 'bar',
name: 'throw_exception',
stack: 'throw_exception',
itemStyle: {color: '#9f354d'},
data: [256,2933,827,633]
},
{
type: 'bar',
name: 'baremetal.return_val',
stack: 'return_val',
itemStyle: {color: '#26735a'},
data: [13,13,13,16]
},
{
type: 'bar',
name: 'return_val',
stack: 'return_val',
itemStyle: {color: '#5aad92'},
data: [13,13,13,16]
},
{
type: 'bar',
name: 'baremetal.abort',
stack: 'abort',
itemStyle: {color: '#ae6039'},
data: [18,21,21,17]
},
{
type: 'bar',
name: 'abort',
stack: 'abort',
itemStyle: {color: '#FFAE84'},
data: [18,21,33,17]
},
{
type: 'bar',
name: 'noexcept_abort',
stack: 'noexcept_abort',
itemStyle: {color: '#589832'},
barCategoryGap: '10%',
data: [18,21,13647,6100]
}
];
var data_Cost2ndError = [
{
type: 'bar',
name: 'throw_exception',
stack: 'throw_exception',
itemStyle: {color: '#9f354d'},
data: [66,60,68,41]
},
{
type: 'bar',
name: 'baremetal.return_val',
stack: 'return_val',
itemStyle: {color: '#26735a'},
data: [19,19,22,15]
},
{
type: 'bar',
name: 'return_val',
stack: 'return_val',
itemStyle: {color: '#5aad92'},
data: [19,19,22,15]
},
{
type: 'bar',
name: 'baremetal.abort',
stack: 'abort',
itemStyle: {color: '#ae6039'},
data: [20,23,24,15]
},
{
type: 'bar',
name: 'abort',
stack: 'abort',
itemStyle: {color: '#FFAE84'},
data: [20,23,36,15]
},
{
type: 'bar',
name: 'noexcept_abort',
stack: 'noexcept_abort',
itemStyle: {color: '#589832'},
barCategoryGap: '10%',
data: [20,23,60,56]
},
];
var data_Cost1stCatch = [
{
type: 'bar',
name: 'throw_exception',
stack: 'throw_exception',
itemStyle: {color: '#9f354d'},
data: [53,63,77,126]
},
{
type: 'bar',
name: 'baremetal.return_val',
stack: 'return_val',
itemStyle: {color: '#26735a'},
data: [14,14,19,18]
},
{
type: 'bar',
name: 'return_val',
stack: 'return_val',
itemStyle: {color: '#5aad92'},
data: [14,14,19,18]
}
];
var data_Cost2ndCatch = [
{
type: 'bar',
name: 'throw_exception',
stack: 'throw_exception',
itemStyle: {color: '#9f354d'},
data: [29,34,25,64]
},
{
type: 'bar',
name: 'baremetal.return_val',
stack: 'return_val',
itemStyle: {color: '#26735a'},
data: [20,14,16,16]
},
{
type: 'bar',
name: 'return_val',
stack: 'return_val',
itemStyle: {color: '#5aad92'},
data: [28,14,16,16]
}
];
</script>
<script src="echarts_modified.js"></script>
<script type="text/javascript">
function addCommas(x) {
x = (x + '').split('.');
return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
+ (x.length > 1 ? ('.' + x[1]) : '');
}
function myFormatter(params, ticket, callback) {
colorText = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' +
params.color +
';"></span>';
return params.seriesName + "<br />" + colorText + params.name + ": " + addCommas(params.value) + " bytes";
}
</script>
<style>
blockquote.book {
display: block;
border-width: 2px 0;
border-style: solid;
border-color: #eee;
padding: 1.5em 5em 0.5em 5em;
margin: 1.5em 0;
position: relative;
text-align: justify;
}
blockquote.book:before {
content: '\201C';
position: absolute;
top: 0em;
left: 50%;
transform: translate(-50%, -50%);
background: #fff;
width: 3rem;
height: 2rem;
font: 6em/1.08em 'PT Sans', sans-serif;
color: #666;
text-align: center;
}
blockquote.book:after {
content: '\201D';
position: absolute;
bottom: -0.25em;
left: 50%;
transform: translate(-50%, -50%);
background: #fff;
width: 3rem;
height: 2rem;
font: 6em/1.08em 'PT Sans', sans-serif;
color: #666;
text-align: center;
}
cite {
display: block;
text-align: right;
color: #e74c3c;
margin: 0 -5em 1em 0;
}
</style>
<blockquote class="book">
To make progress, we need better data on costs and performance to evaluate the - often simplistic and narrowly focused - solutions suggested.
<cite>— Direction for ISO C++ <sup>[[P0939R2]]</sup></cite>
</blockquote>
Introduction {#intro}
====================================
In this paper, we will look at the *size* costs of error handling. We'll break things down into one-time costs and incremental costs, and subdivide by costs paid for error neutral functions, raising an error, and handling an error.
Changes {#changes}
====================================
R1 of this paper removed the discussion on how exceptions are implemented, and reduced the set of error handling strategies down to throwing exceptions, return codes, abort, and noexcept abort. This is to make the paper and charts easier to read. The data is the same.
R1 renamed the "stripped" cases to "baremetal" cases, to better frame where those numbers would be applicable.
Measuring methodology {#methodology}
====================================
All benchmarks lie. It's important to know how a benchmark is set up so that the useful parts can be distinguished from the misleading parts.
The specific build flags can be found in [Appendix B](#build_flags). Following is a brief summary.
MSVC 2019 was used for MSVC x86 and MSVC x64 builds. The /d2FH4 flag described in [[MoFH4]] was used, and /EHs was used when exceptions were on.
GCC 7.3.1 from the Red Hat Developer Toolset 7.1 was used for my GCC builds. The Linux x64 platform was targeted.
Clang 8.0.0, libc++, and libc++abi was used for my Clang builds. The Linux x64 platform was targeted. The system linker and C library leaked in to this build. The system GCC was GCC 4.8.4 from Ubuntu 14.04.3.
All the binaries are optimized for size, rather than speed.
All the binaries are built with static runtimes, so that we can also see the costs of the error handling runtime machinery. For many people, this is a sunk cost. If the cost of the runtime machinery isn't of interest, then don't pay attention to the one-time costs, and just look at the incremental costs. Sizes were not calculated by just doing the "easy" thing and comparing the on-disk sizes of the resulting programs. Programs have lots and lots of padding internal to them due to alignment constraints, and that padding can mask or inflate small cost changes. Instead, the size is calculated by summing the size of all the non-code sections, and by summing the size of each function in the code sections. Measuring the size of a function is a little tricky, as the compiler doesn't emit that information directly. There are often padding instructions between consecutive functions. My measurements omit the padding instructions so that we can see code size differences as small as one byte.
Measurements are also included where the size of some data sections related to unwinding are omitted. On x64 Linux, programs can have an .eh_frame and .eh_frame_hdr section that can help with emitting back traces. x64 Windows has similar sections named .xdata and .pdata. These sections aren't sufficient to implement C++ exception handling, and they don't go away when exceptions are turned off. On Linux and Windows, these sections should be considered a sunk cost, but on more exotic platforms, it is reasonable to omit those sections, as stack trace costs may not be tolerable. These measurements are all labeled as "baremetal". x86 Windows doesn't have these sections, so the "baremetal" measurements are the same as the regular measurements.
Note that on Linux, the entire user mode program can be statically linked. This is the program under test, the C++ runtime, the C runtime, and any OS support. On Windows, the program, the C++ runtime, and the C runtime can be statically linked, but the OS support (kernel32.dll) is still distinct. With this in mind, refrain from comparing the one-time MSVC sizes to the Clang and GCC sizes, as it isn't comparing the same set of functionality.
These benchmarks are run on very small programs. On larger programs, various code and data deduplication optimizations could substantially change the application-level costs of error handling. [[MoFH4]] documents the kinds of deduplication that MSVC 2019 performs.
Starter test cases {#starter_case}
=====================
To start with, we will look at code similar to the following:
```
struct Dtor {~Dtor() {}};
int global_int = 0;
void callee() {/* will raise an error one day*/}
void caller() {
Dtor d;
callee();
global_int = 0;
}
int main() {
caller();
return global_int;
}
```
This code has some important properties for future comparisons.
* `callee()` will eventually raise errors.
* `caller()` needs to clean up the `d` object in error and non-error conditions.
* `caller()` should only set `global_int` in success cases.
* The code doesn't have any error cases yet. We can see the cost of error handling machinery when no errors are involved.
In the actual tests all the function bodies are in separate .cpp files, and link-time / whole-program optimizations aren't used. If they had been used, the entire program would get optimized away, removing our ability to measure error handling differences.
The above program is a useful template when using exceptions or `std::abort` as an error handling mechanism, but it won't work as well for error codes. So we mutate the program like so...
```
int callee() {return 0;}
int caller() {
Dtor d;
int e = callee();
if (e)
return e;
global_int = 0;
return e;
}
```
This is pretty typical integer return value code, without any macro niceties.
Most of the programs were built with exceptions turned off, but the throw_* cases and noexcept_abort all had exceptions turned on in the program.
* abort: When an error is encountered, kill the program with `std::abort`.
* noexcept_abort: Same as abort, except exceptions are turned on, and all the functions declared in user source are marked as `noexcept`.
* return_val: Return an integer error code, where zero represents success.
* throw_exception: Throw an exception deriving from std::exception, that contains only an int. This should represent more typical use cases.
Data on many more error handling strategies can be found in <a href="https://wg21.link/P1640R0">R0</a> of this paper.
Expository code for all the cases can be found in [Appendix C](#code). The actual code used for the benchmark can be found [on my github](https://github.com/ben-craig/error_bench/tree/8807ec200b7992294490e8754847dce648a3eadb/src).
Measurements {#measurements}
============================
Initial error neutral size cost {#neutral1}
-----------------------
My first batch of measurements is comparing each of the mechanisms to the baremetal.abort test case. This lets us focus on the incremental costs of the other mechanisms.
<p align="center"><i>Warning! Logarithmic axis! Linear version [here](#linearneutral1)</i></p>
<div id="CmpTerm" style="width: 100%;height:300px;"></div>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('CmpTerm'));
// specify chart configuration item and data
var option = {
tooltip: { formatter: myFormatter },
calculable : true,
legend: {
type: 'scroll',
right: 0,
top: 0,
orient: 'vertical',
},
xAxis: [{
type: 'log',
min: 1,
max: 400000
}],
yAxis: [{
type: 'category',
data: ['Clang','GCC','MSVC x64','MSVC x86']
}],
grid: {
top: 0,
left: 65,
right: 200
},
series: data_CmpTerm
};
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
<p align="center"><i>Warning! Logarithmic axis! Linear version [here](#linearneutral1)</i></p>
These tables show us that the one-time cost for exceptions is really high (6KB on MSVC x86, 382KB on Clang x64), and the one time cost for unwind information is pretty high too (6KB on MSVC x64, 57KB on Clang). Note that noexcept_abort has the same cost as regular abort right now. If everything is `noexcept`, the exception machinery costs are not incurred.
Incremental error neutral size cost {#neutral2}
---------------------------------------------
To measure the incremental cost of error neutral code, the code will be updated as follows:
```
void callee2(int amount) {
global_int += amount;
// will error one day
}
void caller2(int amount) {
Dtor d;
callee2(amount);
global_int += amount;
}
int main() {
caller();
caller2(0);
return global_int;
}
```
The "2" versions of these functions are slightly different than the original versions in order to avoid optimization where identical code is de-duplicated (COMDAT folding). Each error handling case was updated to the idiomatic form that had the same semantics as this error neutral form. Here are the incremental numbers:
<div id="SecondNeutral" style="width: 100%;height:300px;"></div>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('SecondNeutral'));
// specify chart configuration item and data
var option = {
tooltip: { formatter: myFormatter },
calculable : true,
legend: {
type: 'scroll',
right: 0,
top: 0,
orient: 'vertical',
},
xAxis: [{
type: 'value',
}],
yAxis: [{
type: 'category',
data: ['Clang','GCC','MSVC x64','MSVC x86']
}],
grid: {
top: 0,
left: 65,
right: 200
},
dataZoom: [{show: true}],
series: data_Cost2ndNeutral
};
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
The delta between the best and the worst is much smaller in the incremental error neutral measurements than in the one-time cost measurements. `abort` and return values were always cheaper than exceptions, even with included unwind information.
Initial size cost of signaling an error {#error1}
------------------------------------
What happens when an error is signaled first time? What's the one-time cost of that first error?
```
void callee() {
if (global_int == INT_MAX)
throw 1;
}
```
<p align="center"><i>Warning! Logarithmic axis! Linear version [here](#linearerror1)</i></p>
<div id="FirstError" style="width: 100%;height:300px;"></div>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('FirstError'));
// specify chart configuration item and data
var option = {
tooltip: { formatter: myFormatter },
calculable : true,
legend: {
type: 'scroll',
right: 0,
top: 0,
orient: 'vertical',
},
xAxis: [{
type: 'log',
min: 1,
max: 250000
}],
yAxis: [{
type: 'category',
data: ['Clang','GCC','MSVC x64','MSVC x86']
}],
grid: {
top: 0,
left: 65,
right: 200
},
series: data_Cost1stError
};
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
<p align="center"><i>Warning! Logarithmic axis! Linear version [here](#linearerror1)</i></p>
On MSVC, there are multiple ways to build with exceptions "on". This experiment was built with `/EHs`, which turns on exceptions in a C++ conforming manner. The Microsoft recommended flag is `/EHsc`, which turns on exceptions for all C++ functions, but assumes that `extern "C"` functions won't throw. This is a useful, though non-conforming option. The trick is that the noexcept_abort `callee()` implementation calls `abort()`, and that's an `extern "C"` function that isn't marked as `noexcept`, so we suddenly need to pay for all the exception handling costs that we had been avoiding by making everything `noexcept`. We can't easily make the C runtime, or other people's code `noexcept`. We don't see this on GCC and Clang because the C library they are calling marks abort as `__attribute__ ((__nothrow__))`, and that lets them avoid generating the exception machinery.
GCC's first throw costs look worse than Clang's because Clang paid a lot of those costs even before there was a throw.
Incremental size cost of signaling an error {#error2}
----------------------------------------------
```
void callee2(int amount) {
if (global_int + amount == INT_MAX)
throw 1;
global_int += amount;
}
```
<div id="SecondError" style="width: 100%;height:300px;"></div>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('SecondError'));
// specify chart configuration item and data
var option = {
tooltip: { formatter: myFormatter },
calculable : true,
legend: {
type: 'scroll',
right: 0,
top: 0,
orient: 'vertical',
},
xAxis: [{
type: 'value',
}],
yAxis: [{
type: 'category',
data: ['Clang','GCC','MSVC x64','MSVC x86']
}],
grid: {
top: 0,
left: 65,
right: 200
},
dataZoom: [{show: true}],
series: data_Cost2ndError
};
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
These numbers are all over the place. Here are some highlights:
* On GCC and Clang, throwing an exception is more incrementally expensive than all the non-throwing variants.
* On MSVC, it isn't just the first non-`noexcept` function that is expensive in noexcept_abort, but the later calls are expensive too.
Initial size cost for handling an error {#handle1}
---------------------------------------------
To get the initial handling costs, we'll rewrite main to look something like this...
```
int main() {
try {
caller();
} catch (int) {
global_int = 0;
}
caller2(0);
return global_int;
}
```
`abort` results won't be included here, because there is no "handling" of an `abort` call in C++. The environment needs to handle it and restart the process, reboot the system, or relaunch the rocket.
<div id="FirstCatch" style="width: 100%;height:200px;"></div>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('FirstCatch'));
// specify chart configuration item and data
var option = {
tooltip: { formatter: myFormatter },
calculable : true,
legend: {
type: 'scroll',
right: 0,
top: 0,
orient: 'vertical',
},
xAxis: [{
type: 'value',
}],
yAxis: [{
type: 'category',
data: ['Clang','GCC','MSVC x64','MSVC x86']
}],
grid: {
top: 0,
left: 65,
right: 200
},
dataZoom: [{show: true}],
series: data_Cost1stCatch
};
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
Here we see that the initial catch cost exceptions is high compared to the alternatives.
Incremental size cost for handling an error {#handle2}
-------------------------------------------------
Now for the incremental code, and the associated costs.
```
int main() {
try {
caller();
} catch (int) {
global_int = 0;
}
try {
caller2(0);
} catch (int) {
global_int = 0;
}
return global_int;
}
```
Note that this is measuring the cost of handling a second error within a single function. If the error handling were split over multiple functions, the cost profile may be different.
<div id="SecondCatch" style="width: 100%;height:200px;"></div>
<script type="text/javascript">
// based on prepared DOM, initialize echarts instance
var myChart = echarts.init(document.getElementById('SecondCatch'));
// specify chart configuration item and data
var option = {
tooltip: { formatter: myFormatter },
calculable : true,
legend: {
type: 'scroll',
right: 0,
top: 0,
orient: 'vertical',
},
xAxis: [{
type: 'value',
}],
yAxis: [{
type: 'category',
data: ['Clang','GCC','MSVC x64','MSVC x86']
}],
grid: {
top: 0,
left: 65,
right: 200
},
dataZoom: [{show: true}],
series: data_Cost2ndCatch
};
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
Conclusion {#conclusion}
========================
Exceptions and on-by-default unwinding information are reasonable error handling strategies in many environments, but they don't serve all needs in all use cases. C++ needs standards conforming ways to avoid exception and unwind overhead on platforms that are size constrained. C++ is built on the foundation that you don't pay for what you don't use, and that you can't write the language abstractions better by hand. This paper provides evidence that you can write error handling code by hand that results in smaller code than the equivalent exception throwing code if all you use is terminate semantics or an integer's worth of error information. In each of the six test cases, terminate and integer return values beat exceptions on size, even before stripping out unwind information.
Acknowledgments {#ack}
======================
Simon Brand, Niall Douglas, Brad Keryan, Reid Kleckner, Modi Mo, Herb Sutter, John McFarlane, Ben Saks, and Richard Smith provided valuable review commentary on R0 of this paper.
Thanks to Lawrence Crowl, for asking the question "what if everything were `noexcept`?".
Charts generated with [[ECharts]].
Appendix A: Why no speed measurements? {#speed}
=======================================
[[P1886]] contains speed measurements for various error handling strategies.
Appendix B: The build flags {#build_flags}
============================
MSVC {#msvc}
--------------------
The compiler and flags are the same for 32-bit and 64-bit builds, except that the 32-bit linker uses /machine:x86 and the 64-bit linker uses /machine:x64
Compiler marketing version: Visual Studio 2019
Compiler toolkit version: 14.20.27508
cl.exe version: 19.20.27508.1
Compiler codegen flags (no exceptions): /GR /Gy /Gw /O1 /MT /d2FH4 /std:c++latest /permissive- /DNDEBUG
Compiler codegen flags (with exceptions): /EHs /GR /Gy /Gw /O1 /MT /d2FH4 /std:c++latest /permissive- /DNDEBUG
Linker flags: /OPT:REF /release /subsystem:CONSOLE /incremental:no /OPT:ICF /NXCOMPAT /DYNAMICBASE /DEBUG *.obj
Clang x64 {#clang_x64}
----------------------
Toolchains used:
* Clang 8.0.0 and libc++
* System linker from Ubuntu 14.04.3's GCC 4.8.4 installation
Compiler codegen flags (no exceptions): -fno-exceptions -Os -ffunction-sections -fdata-sections -std=c++17 -stdlib=libc++ -static -DNDEBUG
Compiler codegen flags (exceptions): -Os -ffunction-sections -fdata-sections -std=c++17 -stdlib=libc++ -static -DNDEBUG
Linking flags: -Wl,--gc-sections -pthread -static -static-libgcc -stdlib=libc++ *.o libc++abi.a
GCC x64 {#gcc_x64}
------------------
Toolchain used: GCC 7.3.1 from the Red Hat Developer Toolset 7.1
Compiler codegen flags (no exceptions): -fno-exceptions -Os -ffunction-sections -fdata-sections -std=c++17 -static
Compiler codegen flags (exceptions): -Os -ffunction-sections -fdata-sections -std=c++17 -static
Linking flags: -Wl,--gc-sections -pthread -static -static-libgcc -static-libstdc++ *.o
Appendix C: The code {#code}
============================
As stated before, this isn't the exact code that was benchmarked. In the benchmarked code, functions were placed in distinct translation units in order to avoid inlining. The following code is provided to demonstrate what the error handling code looks like.
Common support code {#code_support}
---------------------------------------
<details>
<summary>Expand to see code snippets</summary>
**All cases**
```
struct Dtor {~Dtor() {}};
int global_int = 0;
```
**throw_exception**
```
class err_exception : public std::exception {
public:
int val;
explicit err_exception(int e) : val(e) {}
const char *what() const noexcept override { return ""; }
};
```
</details>
Initial error neutral functions {#code_neutral1}
---------------------------------------
This section lays the groundwork for future comparisons. All of these cases are capable of transporting error information from a future signaling site (`callee`) to a future catching site (`main`). No errors are signaled here, but the plumbing is in place.
<details>
<summary>Expand to see code snippets</summary>
**Default main function**
```
int main() {
caller();
return global_int;
}
```
**abort, throw_exception**
```
void callee() {/* will raise an error one day*/}
void caller() {
Dtor d;
callee();
global_int = 0;
}
```
**noexcept_abort**
```
void callee() noexcept {/* will raise an error one day*/}
void caller() noexcept {
Dtor d;
callee();
global_int = 0;
}
```
**return_val**
```
int callee() noexcept {return 0;}
int caller() noexcept {
Dtor d;
int e = callee();
if (e)
return e;
global_int = 0;
return e;
}
```
</details>
Incremental error neutral functions {#code_neutral2}
---------------------------------------
Here, we add an extra two functions with error transporting capabilities so that we can measure the incremental cost of error neutral functions. These functions need to be slightly different than the old functions in order to avoid deduplication optimizations.
In order to save on text length, the only functions that will be listed here are the functions were added or changed compared to the previous section.
<details>
<summary>Expand to see code snippets</summary>
**Default main function**
```
int main() {
caller();
caller2(0);
return global_int;
}
```
**abort, throw_exception**
```
void callee2(int amount) { global_int += amount; }
void caller2(int amount) {
Dtor d;
callee2(amount);
global_int += amount;
}
```
**noexcept_abort**
```
void callee2(int amount) noexcept { global_int += amount; }
void caller2(int amount) noexcept {
Dtor d;
callee2(amount);
global_int += amount;
}
```
**return_val**
```
int callee2(int amount) {
global_int += amount;
return 0;
}
int caller2(int amount) {
Dtor d;
int e = callee2(amount);
if (e)
return e;
global_int += amount;
return e;
}
```
</details>
Initial signaling of an error {#code_error1}
---------------------------------------
<details>
<summary>Expand to see code snippets</summary>
**abort**
```
void callee() {
if (global_int == INT_MAX)
abort();
}
```
**noexcept_abort**
```
void callee() noexcept {
if (global_int == INT_MAX)
abort();
}
```
**return_val**
```
int callee() {
if (global_int == INT_MAX) {
return 1;
}
return 0;
}
```
**throw_exception**
```
void callee() {
if (global_int == INT_MAX)
throw err_exception(1);
}
```
</details>
Incremental signaling of an error {#code_error2}
---------------------------------------
<details>
<summary>Expand to see code snippets</summary>
**abort**
```
void callee2(int amount) {
if (global_int + amount == INT_MAX)
abort();
global_int += amount;
}
```
**noexcept_abort**
```
void callee2(int amount) noexcept {
if (global_int + amount == INT_MAX)
abort();
global_int += amount;
}
```
**return_val**
```
int callee2(int amount) {
if (global_int + amount == INT_MAX) {
return 1;
}
global_int += amount;
return 0;
}
```
**throw_exception**
```
void callee2(int amount) {
if (global_int + amount == INT_MAX)
throw err_exception(1);
global_int += amount;
}
```
</details>
Initial handling of an error {#code_catch1}
---------------------------------------
<details>
<summary>Expand to see code snippets</summary>
**return_val**
```
int main() {
if (caller()) {
global_int = 0;
}
caller2(0);
return global_int;
}
```
**return_struct**
```
int main() {
if (caller().error) {
global_int = 0;
}
caller2(0);
return global_int;
}
```
**throw_exception**
```
int main() {
try { caller(); }
catch (const std::exception &) {
global_int = 0;
}
caller2(0);
return global_int;
}
```
</details>
Incremental handling of an error {#code_catch2}
---------------------------------------
<details>
<summary>Expand to see code snippets</summary>