-
Notifications
You must be signed in to change notification settings - Fork 7
/
exceptions.cpp
37 lines (31 loc) · 1.02 KB
/
exceptions.cpp
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
#include <cmath>
#include <span>
struct InvalidValue {};
static void doSqrt(std::span<double> values) __attribute__((noinline));
static void doSqrt(std::span<double> values) {
for (auto& v : values) {
if (v < 0) throw InvalidValue{};
v = sqrt(v);
}
}
unsigned exceptionsSqrt(std::span<double> values, unsigned repeat) {
unsigned failures = 0;
for (unsigned index = 0; index != repeat; ++index) {
try {
doSqrt(values);
} catch (const InvalidValue& v) { ++failures; }
}
return failures;
}
// prevent the compile from recognizing and compiling away the fib logic
static unsigned doFib(unsigned n, unsigned maxDepth) __attribute((noinline, optimize("-O1")));
static unsigned doFib(unsigned n, unsigned maxDepth) {
if (!maxDepth) throw InvalidValue();
if (n <= 2) return 1;
return doFib(n - 2, maxDepth - 1) + doFib(n - 1, maxDepth - 1);
}
unsigned exceptionsFib(unsigned n, unsigned maxDepth) {
try {
return doFib(n, maxDepth);
} catch (const InvalidValue&) { return 0; }
}