PolyFEM
Loading...
Searching...
No Matches
Timer.hpp
Go to the documentation of this file.
1#pragma once
2
3// clang-format off
4#include <spdlog/fmt/bundled/color.h>
6// clang-format on
7
8#include <igl/Timer.h>
9
10#define POLYFEM_SCOPED_TIMER(...) polyfem::utils::Timer __polyfem_timer(__VA_ARGS__)
11
12namespace polyfem
13{
14 namespace utils
15 {
16 struct Timing
17 {
18 operator double() const { return time; }
19
20 void operator+=(const double t)
21 {
22 time += t;
23 ++count;
24 }
25
26 double time = 0;
27 size_t count = 0;
28 };
29
30 class Timer
31 {
32 public:
34 {
35 start();
36 }
37
38 Timer(const std::string &name)
39 : m_name(name)
40 {
41 start();
42 }
43
44 Timer(double &total_time)
45 : m_total_time(&total_time)
46 {
47 start();
48 }
49
50 Timer(Timing &timing)
51 : m_total_time(&timing.time), m_count(&timing.count)
52 {
53 start();
54 }
55
56 Timer(const std::string &name, double &total_time)
57 : m_name(name), m_total_time(&total_time)
58 {
59 start();
60 }
61
62 Timer(const std::string &name, Timing &timing)
63 : m_name(name), m_total_time(&timing.time), m_count(&timing.count)
64 {
65 start();
66 }
67
68 virtual ~Timer()
69 {
70 stop();
71 }
72
73 inline void start()
74 {
75 is_running = true;
76 m_timer.start();
77 }
78
79 inline void stop()
80 {
81 if (!is_running)
82 return;
83 m_timer.stop();
84 is_running = false;
85 log_msg();
86 if (m_total_time)
88 if (m_count)
89 ++(*m_count);
90 }
91
92 inline double getElapsedTimeInSec()
93 {
94 return m_timer.getElapsedTimeInSec();
95 }
96
97 inline void log_msg()
98 {
99 const static std::string log_fmt_text =
100 fmt::format("[{}] {{}} {{:.3g}}s", fmt::format(fmt::fg(fmt::terminal_color::magenta), "timing"));
101
102 if (!m_name.empty())
103 {
104 logger().trace(log_fmt_text, m_name, getElapsedTimeInSec());
105 }
106 }
107
108 inline const igl::Timer &igl_timer()
109 {
110 return m_timer;
111 }
112
113 protected:
114 std::string m_name;
115 igl::Timer m_timer;
116 double *m_total_time = nullptr;
117 size_t *m_count = nullptr;
118 bool is_running = false;
119 };
120 } // namespace utils
121} // namespace polyfem
const igl::Timer & igl_timer()
Definition Timer.hpp:108
Timer(const std::string &name, Timing &timing)
Definition Timer.hpp:62
Timer(const std::string &name, double &total_time)
Definition Timer.hpp:56
std::string m_name
Definition Timer.hpp:114
double * m_total_time
Definition Timer.hpp:116
Timer(Timing &timing)
Definition Timer.hpp:50
Timer(double &total_time)
Definition Timer.hpp:44
igl::Timer m_timer
Definition Timer.hpp:115
Timer(const std::string &name)
Definition Timer.hpp:38
double getElapsedTimeInSec()
Definition Timer.hpp:92
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:42
void operator+=(const double t)
Definition Timer.hpp:20