1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <limits>
18 
19 #include "gtest/gtest.h"
20 
21 constexpr int kNumIterations = 1e8;
22 
TEST(FPPerf,Adds)23 TEST(FPPerf, Adds) {
24   double x = 0.0;
25   for (int i = 0; i < kNumIterations; i++) {
26     x += 3.14159265359;
27   }
28   EXPECT_NEAR(x, 3.14159265359 * kNumIterations, static_cast<double>(kNumIterations) / 1e8);
29 }
30 
TEST(FPPerf,TinyAdds)31 TEST(FPPerf, TinyAdds) {
32   double x = 0.0;
33   for (int i = 0; i < kNumIterations; i++) {
34     x += std::numeric_limits<double>::min();
35   }
36   EXPECT_DOUBLE_EQ(x, std::numeric_limits<double>::min() * kNumIterations);
37 }
38 
TEST(FPPerf,OverflowingAdds)39 TEST(FPPerf, OverflowingAdds) {
40   double x = 1.0e308;
41   for (int i = 0; i < kNumIterations; i++) {
42     x += x;
43   }
44   EXPECT_EQ(x, std::numeric_limits<double>::infinity());
45 }
46 
TEST(FPPerf,OverflowingMuls)47 TEST(FPPerf, OverflowingMuls) {
48   double x = 1.0e308;
49   for (int i = 0; i < kNumIterations; i++) {
50     x *= 3.14159265359;
51   }
52   EXPECT_EQ(x, std::numeric_limits<double>::infinity());
53 }
54 
TEST(FPPerf,UnderflowingMuls)55 TEST(FPPerf, UnderflowingMuls) {
56   volatile double x = 1.0e-307;
57   for (int i = 0; i < kNumIterations; i++) {
58     x *= 0.0314159265359;
59   }
60   EXPECT_EQ(x, 0.0);
61 }
62