|
| 1 | +// (C) Copyright 2017, Google Inc. |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +// Unless required by applicable law or agreed to in writing, software |
| 7 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +// See the License for the specific language governing permissions and |
| 10 | +// limitations under the License. |
| 11 | +// Portability include to match the Google test environment. |
| 12 | + |
| 13 | +#ifndef TESSERACT_UNITTEST_CYCLETIMER_H |
| 14 | +#define TESSERACT_UNITTEST_CYCLETIMER_H |
| 15 | + |
| 16 | +#include "absl/time/clock.h" // for GetCurrentTimeNanos |
| 17 | + |
| 18 | +// See https://github.com/google/or-tools/blob/master/ortools/base/timer.h |
| 19 | +class CycleTimer { |
| 20 | +public: |
| 21 | + CycleTimer() { |
| 22 | + Reset(); |
| 23 | + } |
| 24 | + |
| 25 | + void Reset() { |
| 26 | + running_ = false; |
| 27 | + sum_ = 0; |
| 28 | + } |
| 29 | + |
| 30 | + // When Start() is called multiple times, only the most recent is used. |
| 31 | + void Start() { |
| 32 | + running_ = true; |
| 33 | + start_ = absl::GetCurrentTimeNanos(); |
| 34 | + } |
| 35 | + |
| 36 | + void Restart() { |
| 37 | + sum_ = 0; |
| 38 | + Start(); |
| 39 | + } |
| 40 | + |
| 41 | + void Stop() { |
| 42 | + if (running_) { |
| 43 | + sum_ += absl::GetCurrentTimeNanos() - start_; |
| 44 | + running_ = false; |
| 45 | + } |
| 46 | + } |
| 47 | + int64_t GetInMs() const { return GetNanos() / 1000000; } |
| 48 | + |
| 49 | + protected: |
| 50 | + int64_t GetNanos() const { |
| 51 | + return running_ ? absl::GetCurrentTimeNanos() - start_ + sum_ : sum_; |
| 52 | + } |
| 53 | + |
| 54 | + private: |
| 55 | + bool running_; |
| 56 | + int64_t start_; |
| 57 | + int64_t sum_; |
| 58 | +}; |
| 59 | + |
| 60 | +#endif // TESSERACT_UNITTEST_CYCLETIMER_H |
0 commit comments