OGS
Time.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (c) OpenGeoSys Community (opengeosys.org)
2// SPDX-License-Identifier: BSD-3-Clause
3
4#pragma once
5
6#include <algorithm>
7#include <cmath>
8#include <compare>
9#include <iomanip>
10#include <limits>
11
12#include "MathLib/KahanSum.h"
13
14namespace NumLib
15{
16struct Time;
17}
18
19template <>
20struct fmt::formatter<NumLib::Time> : fmt::ostream_formatter
21{
22};
23
24namespace NumLib
25{
26struct Time
27{
28 constexpr explicit Time(double const time) : value_{time} {}
29
30 constexpr double operator()() const { return value_(); }
31
32 constexpr Time& operator+=(double const increment)
33 {
34 value_ += increment;
35 return *this;
36 }
37
38 constexpr Time operator+(double const increment) const
39 {
40 Time result = *this;
41 result += increment;
42 return result;
43 }
44
45 constexpr Time& operator-=(double const decrement)
46 {
47 value_ -= decrement;
48 return *this;
49 }
50
51 constexpr Time operator-(double const decrement) const
52 {
53 Time result = *this;
54 result -= decrement;
55 return result;
56 }
57
58 constexpr inline std::weak_ordering operator<=>(Time const& b) const
59 {
60 Time const& a = *this;
61 double const diff = b() - a();
62
63 double const eps = 10 * std::numeric_limits<double>::epsilon() *
64 std::max(1., (std::abs(a()) + std::abs(b())) / 2);
65
66 // Keep for debugging
67 // DBUG("Compare {} to {}. x is {} and y is {}. Eps {}, diff {}", a, b,
68 // x, y, eps, diff);
69
70 if (diff < -eps)
71 {
72 return std::weak_ordering::greater;
73 }
74 if (diff > eps)
75 {
76 return std::weak_ordering::less;
77 }
78 return std::weak_ordering::equivalent;
79 }
80
81 constexpr inline bool operator==(Time const& x) const
82 {
83 return (*this <=> x) == std::weak_ordering::equivalent;
84 }
85
86 friend inline std::ostream& operator<<(std::ostream& os, Time const& t)
87 {
88 auto const precision = os.precision();
89 return os << std::setprecision(
90 std::numeric_limits<double>::max_digits10)
91 << t() << std::setprecision(precision);
92 }
93
94private:
96};
97
98} // namespace NumLib
constexpr Time(double const time)
Definition Time.h:28
constexpr double operator()() const
Definition Time.h:30
constexpr bool operator==(Time const &x) const
Definition Time.h:81
friend std::ostream & operator<<(std::ostream &os, Time const &t)
Definition Time.h:86
constexpr Time & operator+=(double const increment)
Definition Time.h:32
MathLib::KahanSum value_
Definition Time.h:95
constexpr Time operator-(double const decrement) const
Definition Time.h:51
constexpr std::weak_ordering operator<=>(Time const &b) const
Definition Time.h:58
constexpr Time & operator-=(double const decrement)
Definition Time.h:45
constexpr Time operator+(double const increment) const
Definition Time.h:38