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 { |
| 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 | |
| 28 | float timeTaken() const { |
Lorenzo Colitti | 19ee8a8 | 2017-02-02 12:59:05 +0900 | [diff] [blame] | 29 | return getElapsed(clock::now()); |
| 30 | } |
| 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 | } |
| 38 | |
| 39 | private: |
Lorenzo Colitti | 19ee8a8 | 2017-02-02 12:59:05 +0900 | [diff] [blame] | 40 | typedef std::chrono::steady_clock clock; |
| 41 | typedef std::chrono::time_point<clock> time_point; |
| 42 | time_point mStart; |
| 43 | |
| 44 | float getElapsed(const time_point& now) const { |
| 45 | using ms = std::chrono::duration<float, std::ratio<1, 1000>>; |
| 46 | return (std::chrono::duration_cast<ms>(now - mStart)).count(); |
| 47 | } |
Robin Lee | 7e05cc9 | 2016-09-21 16:31:33 +0900 | [diff] [blame] | 48 | }; |
| 49 | |
| 50 | #endif // NETD_INCLUDE_STOPWATCH_H |