blob: 31a921c0e07d438c424009e47b728ff1ff16f967 [file] [log] [blame]
Robin Lee7e05cc92016-09-21 16:31:33 +09001/*
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
22class Stopwatch {
lifr9a729d72018-11-21 22:28:40 +080023 public:
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090024 Stopwatch() : mStart(clock::now()) {}
25
Robin Lee7e05cc92016-09-21 16:31:33 +090026 virtual ~Stopwatch() {};
27
lifr9a729d72018-11-21 22:28:40 +080028 float timeTaken() const { return getElapsed(clock::now()); }
29
30 int64_t timeTakenUs() const { return getElapsedUs(clock::now()); }
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090031
32 float getTimeAndReset() {
33 const auto& now = clock::now();
34 float elapsed = getElapsed(now);
35 mStart = now;
36 return elapsed;
Robin Lee7e05cc92016-09-21 16:31:33 +090037 }
lifr9a729d72018-11-21 22:28:40 +080038 float getTimeAndResetUs() {
39 const auto& now = clock::now();
40 float elapsed = getElapsedUs(now);
41 mStart = now;
42 return elapsed;
43 }
Robin Lee7e05cc92016-09-21 16:31:33 +090044
lifr9a729d72018-11-21 22:28:40 +080045 private:
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090046 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 }
lifr9a729d72018-11-21 22:28:40 +080054 int64_t getElapsedUs(const time_point& now) const {
55 return (std::chrono::duration_cast<std::chrono::microseconds>(now - mStart)).count();
56 }
Robin Lee7e05cc92016-09-21 16:31:33 +090057};
58
59#endif // NETD_INCLUDE_STOPWATCH_H