sliding_counter.cc
1 // Copyright 2020, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 #include "util/uring/sliding_counter.h"
5 
6 #include "base/logging.h"
7 #include "base/walltime.h"
8 
9 using namespace std;
10 
11 namespace util {
12 namespace uring {
13 namespace detail {
14 
15 uint32_t SlidingCounterTLBase::MoveTsIfNeeded(size_t size, int32_t* dest) const {
16  uint32_t current_sec = base::GetClockMicros<CLOCK_MONOTONIC_COARSE>() / 1000000UL;
17  if (last_ts_ + size <= current_sec) {
18  std::fill(dest, dest + size, 0);
19  } else {
20  // Reset delta upto current_time including.
21  for (uint32_t i = last_ts_ + 1; i <= current_sec; ++i) {
22  dest[i % size] = 0;
23  }
24  }
25  last_ts_ = current_sec;
26 
27  return current_sec % size;
28 }
29 
30 void SlidingCounterBase::InitInternal(ProactorPool* pp) {
31  CHECK(pp_ == nullptr);
32  pp_ = CHECK_NOTNULL(pp);
33 }
34 
35 void SlidingCounterBase::CheckInit() const {
36  CHECK_NOTNULL(pp_);
37 }
38 
39 unsigned SlidingCounterBase::ProactorThreadIndex() const {
40  unsigned tnum = CHECK_NOTNULL(pp_)->size();
41 
42  int32_t indx = Proactor::GetIndex();
43  CHECK_GE(indx, 0) << "Must be called from proactor thread!";
44  CHECK_LT(indx, tnum) << "Invalid thread index " << indx;
45 
46  return unsigned(indx);
47 }
48 
49 } // namespace detail
50 } // namespace uring
51 } // namespace util