HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
counters.hpp
1// Copyright 2019 Pokitec
2// All rights reserved.
3
4#pragma once
5
6#include "TTauri/Foundation/wfree_unordered_map.hpp"
7#include <nonstd/span>
8#include <typeinfo>
9#include <typeindex>
10
11namespace tt {
12
13constexpr int MAX_NR_COUNTERS = 1024;
14
16 std::atomic<int64_t> *counter;
17 int64_t previous_value;
18};
19
21
22// To reduce number of executed instruction this is a global varable.
23// The wfree_unordered_map does not need to be initialized.
24inline counter_map_type counter_map;
25
26template<typename Tag>
28 // Make sure non of the counters are false sharing cache-lines.
29 alignas(cache_line_size) inline static std::atomic<int64_t> counter = 0;
30
31 tt_no_inline void add_to_map() const noexcept {
32 counter_map.insert(std::type_index(typeid(Tag)), counter_map_value_type{&counter, 0});
33 }
34
35 int64_t increment() const noexcept {
36 ttlet value = counter.fetch_add(1, std::memory_order_relaxed);
37
38 if (tt_unlikely(value == 0)) {
39 add_to_map();
40 }
41
42 return value + 1;
43 }
44
45 int64_t read() const noexcept {
46 return counter.load(std::memory_order_relaxed);
47 }
48
49 // Don't implement readAndSet, a set to zero would cause the counters to be reinserted.
50};
51
52template<typename Tag>
53inline int64_t increment_counter() noexcept
54{
55 return counter_functor<Tag>{}.increment();
56}
57
58template<typename Tag>
59inline int64_t read_counter() noexcept
60{
61 return counter_functor<Tag>{}.read();
62}
63
67inline std::pair<int64_t, int64_t> read_counter(std::type_index tag) noexcept
68{
69 auto &item = counter_map[tag];
70
71 ttlet * const count_ptr = item.counter;
72 ttlet count = count_ptr != nullptr ? item.counter->load(std::memory_order_relaxed) : 0;
73 ttlet count_since_last_read = count - item.previous_value;
74 item.previous_value = count;
75 return {count, count_since_last_read};
76}
77
78}
Definition counters.hpp:15
Definition counters.hpp:27
Definition range_map.hpp:119
Definition wfree_unordered_map.hpp:55
T count(T... args)
T fetch_add(T... args)
T load(T... args)