Alien  1.3.0
Developer documentation
Loading...
Searching...
No Matches
StdTimer.h
1// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
2//-----------------------------------------------------------------------------
3// Copyright 2000-2026 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
4// See the top-level COPYRIGHT file for details.
5// SPDX-License-Identifier: Apache-2.0
6//-----------------------------------------------------------------------------
7#pragma once
8#include <string>
9#include <map>
10#include <chrono>
11
12#ifdef __cpp_lib_format
13#include <format>
14#define HAS_FORMAT 1
15#else
16#define HAS_FORMAT 0
17#endif
18
19namespace Alien
20{
21class StdTimer
22{
23 public:
24 class Sentry
25 {
26 public:
27 Sentry(StdTimer& parent, std::string phase)
28 : m_parent(parent)
29 , m_phase(phase)
30 {
31 m_start = std::chrono::steady_clock::now();
32 }
33
34 virtual ~Sentry()
35 {
36 std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
37 std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(end - m_start);
38
39 m_parent.add(m_phase, time_span.count());
40 }
41
42 private:
43 StdTimer& m_parent;
44 std::string m_phase;
45 std::chrono::steady_clock::time_point m_start;
46 };
47
48 StdTimer() {}
49 virtual ~StdTimer() {}
50
51 void reset() {
52 for (auto& iter : m_counters)
53 iter.second = 0. ;
54 }
55
56 void add(std::string const& phase, double value)
57 {
58 auto iter = m_counters.find(phase);
59 if (iter == m_counters.end())
60 m_counters[phase] = value;
61 else
62 iter->second += value;
63 }
64
65 double operator()(std::string const& phase) const
66 {
67 auto iter = m_counters.find(phase);
68 if (iter == m_counters.end())
69 return 0. ;
70 else
71 return iter->second ;
72 }
73
74 void printInfo(const std::string& msg) const
75 {
76 std::cout << "================================" << std::endl;
77 std::cout << "PERF INFO : " << msg << std::endl;
78 for (auto const& iter : m_counters) {
79#if HAS_FORMAT
80 std::cout << std::format("{:10}:{:.3e}\n",iter.first,iter.second);
81#else
82 std::cout << iter.first<<":"<<iter.second<<std::endl ;
83#endif
84 }
85 std::cout << "================================" << std::endl;
86 }
87
88 void printInfo(std::ostream& out, const std::string& msg) const
89 {
90 out << msg << std::endl;
91 out << "================================" << std::endl;
92 out << "PERF INFO : " << std::endl;
93 for (auto const& iter : m_counters) {
94#if HAS_FORMAT
95 out << std::format("{:10}:{:.3e}\n",iter.first,iter.second);
96#else
97 out << iter.first<<":"<<iter.second<<std::endl ;
98#endif
99 }
100 out << "================================" << std::endl;
101 }
102
103 private:
104 std::map<std::string, double> m_counters;
105};
106} // namespace Alien
-- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature --
Definition BackEnd.h:17