blob: e7b4326455635b45cb8f9180bd199c4f7c8b7c87 [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
Mike Yue7e332f2019-03-13 17:15:48 +080017#ifndef NETDUTILS_STOPWATCH_H
18#define NETDUTILS_STOPWATCH_H
Robin Lee7e05cc92016-09-21 16:31:33 +090019
20#include <chrono>
21
Mike Yue7e332f2019-03-13 17:15:48 +080022namespace android {
23namespace netdutils {
24
Robin Lee7e05cc92016-09-21 16:31:33 +090025class Stopwatch {
Mike Yue7e332f2019-03-13 17:15:48 +080026 private:
27 using clock = std::chrono::steady_clock;
28 using time_point = std::chrono::time_point<clock>;
29
lifr9a729d72018-11-21 22:28:40 +080030 public:
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090031 Stopwatch() : mStart(clock::now()) {}
Mike Yue7e332f2019-03-13 17:15:48 +080032 virtual ~Stopwatch() = default;
Robin Lee7e05cc92016-09-21 16:31:33 +090033
lifr9a729d72018-11-21 22:28:40 +080034 int64_t timeTakenUs() const { return getElapsedUs(clock::now()); }
Bernie Innocenti196f1b82019-05-20 16:34:16 +090035 int64_t getTimeAndResetUs() {
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090036 const auto& now = clock::now();
Bernie Innocenti196f1b82019-05-20 16:34:16 +090037 int64_t elapsed = getElapsedUs(now);
lifr9a729d72018-11-21 22:28:40 +080038 mStart = now;
39 return elapsed;
40 }
Robin Lee7e05cc92016-09-21 16:31:33 +090041
lifr9a729d72018-11-21 22:28:40 +080042 private:
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090043 time_point mStart;
44
lifr9a729d72018-11-21 22:28:40 +080045 int64_t getElapsedUs(const time_point& now) const {
46 return (std::chrono::duration_cast<std::chrono::microseconds>(now - mStart)).count();
47 }
Robin Lee7e05cc92016-09-21 16:31:33 +090048};
49
Mike Yue7e332f2019-03-13 17:15:48 +080050} // namespace netdutils
51} // namespace android
52
53#endif // NETDUTILS_STOPWATCH_H