xref: /aosp_15_r20/external/pigweed/pw_log/rate_limited.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_log/rate_limited.h"
16 
17 namespace pw::log::internal {
18 
Poll(chrono::SystemClock::duration min_interval_between_logs)19 RateLimiter::PollResult RateLimiter::Poll(
20     chrono::SystemClock::duration min_interval_between_logs) {
21   PollResult result({
22       .count = 0,
23       .logs_per_s = 0,
24   });
25   const chrono::SystemClock::time_point now = chrono::SystemClock::now();
26   const chrono::SystemClock::duration elapsed = now - last_timestamp_;
27 
28   if (count_ < std::numeric_limits<uint16_t>::max()) {
29     count_++;
30   }
31 
32   if (last_timestamp_.time_since_epoch().count() != 0 &&
33       elapsed < min_interval_between_logs) {
34     return result;
35   }
36 
37   // Add half to round not floor.
38   uint16_t elapsed_ms =
39       std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
40   if (elapsed_ms != 0) {
41     result.logs_per_s = (count_ * 1000 + 500) / elapsed_ms;
42   }
43   result.count = count_;
44 
45   last_timestamp_ = now;
46   count_ = 0;
47 
48   return result;
49 }
50 
51 }  // namespace pw::log::internal