Robin Lee | 7e05cc9 | 2016-09-21 16:31:33 +0900 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2016 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef NETD_INCLUDE_STOPWATCH_H |
| 18 | #define NETD_INCLUDE_STOPWATCH_H |
| 19 | |
| 20 | #include <chrono> |
| 21 | |
| 22 | class Stopwatch { |
lifr | 9a729d7 | 2018-11-21 22:28:40 +0800 | [diff] [blame^] | 23 | public: |
Lorenzo Colitti | 19ee8a8 | 2017-02-02 12:59:05 +0900 | [diff] [blame] | 24 | Stopwatch() : mStart(clock::now()) {} |
| 25 | |
Robin Lee | 7e05cc9 | 2016-09-21 16:31:33 +0900 | [diff] [blame] | 26 | virtual ~Stopwatch() {}; |
| 27 | |
lifr | 9a729d7 | 2018-11-21 22:28:40 +0800 | [diff] [blame^] | 28 | float timeTaken() const { return getElapsed(clock::now()); } |
| 29 | |
| 30 | int64_t timeTakenUs() const { return getElapsedUs(clock::now()); } |
Lorenzo Colitti | 19ee8a8 | 2017-02-02 12:59:05 +0900 | [diff] [blame] | 31 | |
| 32 | float getTimeAndReset() { |
| 33 | const auto& now = clock::now(); |
| 34 | float elapsed = getElapsed(now); |
| 35 | mStart = now; |
| 36 | return elapsed; |
Robin Lee | 7e05cc9 | 2016-09-21 16:31:33 +0900 | [diff] [blame] | 37 | } |
lifr | 9a729d7 | 2018-11-21 22:28:40 +0800 | [diff] [blame^] | 38 | float getTimeAndResetUs() { |
| 39 | const auto& now = clock::now(); |
| 40 | float elapsed = getElapsedUs(now); |
| 41 | mStart = now; |
| 42 | return elapsed; |
| 43 | } |
Robin Lee | 7e05cc9 | 2016-09-21 16:31:33 +0900 | [diff] [blame] | 44 | |
lifr | 9a729d7 | 2018-11-21 22:28:40 +0800 | [diff] [blame^] | 45 | private: |
Lorenzo Colitti | 19ee8a8 | 2017-02-02 12:59:05 +0900 | [diff] [blame] | 46 | typedef std::chrono::steady_clock clock; |
| 47 | typedef std::chrono::time_point<clock> time_point; |
| 48 | time_point mStart; |
| 49 | |
| 50 | float getElapsed(const time_point& now) const { |
| 51 | using ms = std::chrono::duration<float, std::ratio<1, 1000>>; |
| 52 | return (std::chrono::duration_cast<ms>(now - mStart)).count(); |
| 53 | } |
lifr | 9a729d7 | 2018-11-21 22:28:40 +0800 | [diff] [blame^] | 54 | int64_t getElapsedUs(const time_point& now) const { |
| 55 | return (std::chrono::duration_cast<std::chrono::microseconds>(now - mStart)).count(); |
| 56 | } |
Robin Lee | 7e05cc9 | 2016-09-21 16:31:33 +0900 | [diff] [blame] | 57 | }; |
| 58 | |
| 59 | #endif // NETD_INCLUDE_STOPWATCH_H |