userver
C++ Async Framework
Toggle main menu visibility
Loading...
Searching...
No Matches
cpu_relax.hpp
Go to the documentation of this file.
1
#
pragma
once
2
3
/// @file userver/utils/cpu_relax.hpp
4
/// @brief Helper classes to yield in CPU intensive places
5
6
#
include
<
chrono
>
7
#
include
<
cstddef
>
8
9
#
include
<
userver
/
tracing
/
scope_time
.
hpp
>
10
11
USERVER_NAMESPACE_BEGIN
12
13
namespace
utils
{
14
15
/// Utility to easily pause ScopeTime, e.g. when yielding
16
class
ScopeTimePause
{
17
public
:
18
explicit
ScopeTimePause(tracing::
ScopeTime
* scope);
19
20
/// Pause a ScopeTime, if any
21
void
Pause
();
22
23
/// Unpause the ScopeTime, if any
24
void
Unpause
();
25
26
private
:
27
tracing::
ScopeTime
* scope_;
28
std::string scope_name_;
29
};
30
31
/// Utility to yield every N iterations in a CPU-bound task to give other tasks
32
/// an opportunity to get CPU time
33
class
CpuRelax
{
34
public
:
35
/// @param every number of iterations to call yield. 0 = noop
36
/// @param scope the tracing::ScopeTime to pause when yielding, if any
37
/// @warning The `ScopeTime` must live at least as long as the `CpuRelax`
38
explicit
CpuRelax
(std::size_t every, tracing::
ScopeTime
* scope);
39
40
CpuRelax(
const
CpuRelax
&) =
delete
;
41
CpuRelax(
CpuRelax
&&) =
delete
;
42
43
/// Call this method every iteration, eventually it will yield
44
void
Relax
() {
45
if
(every_iterations_ == 0) {
46
return
;
47
}
48
if
(++iterations_ == every_iterations_) {
49
iterations_ = 0;
50
DoRelax();
51
}
52
}
53
54
private
:
55
void
DoRelax();
56
57
ScopeTimePause
pause_;
58
const
std::size_t every_iterations_;
59
std::size_t iterations_{0};
60
};
61
62
/// Utility to yield in a CPU-bound data processing task
63
/// to give other tasks an opportunity to get CPU time
64
class
StreamingCpuRelax
{
65
public
:
66
/// @param check_time_after_bytes number of bytes to call yield
67
/// @param scope the tracing::ScopeTime to pause when yielding, if any
68
/// @warning The `ScopeTime` must live at least as long as the `CpuRelax`
69
explicit
StreamingCpuRelax
(std::uint64_t check_time_after_bytes, tracing::
ScopeTime
* scope);
70
71
/// Checks time and potentially calls `engine::Yield()`
72
/// each `check_time_after_bytes` bytes
73
void
Relax
(std::uint64_t bytes_processed);
74
75
/// Returns the total amount of bytes processed since the creation
76
/// of `StreamingCpuRelax`
77
std::
uint64_t
GetBytesProcessed
()
const
;
78
79
private
:
80
ScopeTimePause
pause_;
81
std::uint64_t check_time_after_bytes_;
82
std::uint64_t total_bytes_{0};
83
std::uint64_t bytes_since_last_time_check_{0};
84
std::chrono::steady_clock::time_point last_yield_time_;
85
};
86
87
}
// namespace utils
88
89
USERVER_NAMESPACE_END
userver
utils
cpu_relax.hpp
Generated on
for userver by
Doxygen
1.17.0