sandbox
Loading...
Searching...
No Matches
profiler.hpp
1#ifndef LIBSBX_CORE_PROFILER_HPP_
2#define LIBSBX_CORE_PROFILER_HPP_
3
4#include <string>
5#include <string_view>
6#include <unordered_map>
7#include <ranges>
8
9#include <libsbx/units/time.hpp>
10
11#include <libsbx/utility/hashed_string.hpp>
12
13namespace sbx::core {
14
15class profiler {
16
17public:
18
19 struct group_entry {
20 std::string name;
21 units::second measurement;
22 }; // struct group_entry
23
24 struct group {
25 std::vector<group_entry> entries;
26 units::second overall;
27 }; // struct group
28
29 auto submit(const utility::hashed_string& scope, const units::second& measurement) -> void {
30 _measurements[scope] = measurement;
31 }
32
33 template<typename Callable>
34 requires (std::is_invocable_v<Callable, const utility::hashed_string&, const group&>)
35 auto for_each(Callable&& callable) -> void {
36 auto grouped = std::unordered_map<utility::hashed_string, group>{};
37
38 for (const auto& [scope, measurement] : _measurements) {
39 const auto position = scope.rfind("::");
40
41 const auto has_namespace = (position != utility::hashed_string::npos);
42
43 const auto group = has_namespace ? scope.substr(0, position) : scope;
44 const auto name = has_namespace ? scope.substr(position + 2u) : scope;
45
46 if (!has_namespace) {
47 grouped[group].overall = measurement;
48 } else {
49 grouped[group].entries.emplace_back(name.str(), measurement);
50 }
51 }
52
53 for (auto& [group_name, group] : grouped) {
54 std::sort(group.entries.begin(), group.entries.end(), [](const auto& lhs, const auto& rhs){
55 return lhs.measurement.value() > rhs.measurement.value();
56 });
57
58 std::invoke(callable, group_name, group);
59 }
60 }
61
62private:
63
64 std::unordered_map<utility::hashed_string, units::second> _measurements;
65
66}; // class profiler
67
68} // namespace sbx::core
69
70#endif // LIBSBX_CORE_PROFILER_HPP_
Definition: profiler.hpp:15
Definition: quantity.hpp:65
Definition: hashed_string.hpp:15
Describes a type or object that can be invoked with the give parameters and return the given type.
Definition: concepts.hpp:17
Definition: profiler.hpp:19
Definition: profiler.hpp:24