blob: e7b4326455635b45cb8f9180bd199c4f7c8b7c87 [file] [log] [blame]
Ken Chend27d6c92021-10-21 22:18:59 +08001/*
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 NETDUTILS_STOPWATCH_H
18#define NETDUTILS_STOPWATCH_H
19
20#include <chrono>
21
22namespace android {
23namespace netdutils {
24
25class Stopwatch {
26 private:
27 using clock = std::chrono::steady_clock;
28 using time_point = std::chrono::time_point<clock>;
29
30 public:
31 Stopwatch() : mStart(clock::now()) {}
32 virtual ~Stopwatch() = default;
33
34 int64_t timeTakenUs() const { return getElapsedUs(clock::now()); }
35 int64_t getTimeAndResetUs() {
36 const auto& now = clock::now();
37 int64_t elapsed = getElapsedUs(now);
38 mStart = now;
39 return elapsed;
40 }
41
42 private:
43 time_point mStart;
44
45 int64_t getElapsedUs(const time_point& now) const {
46 return (std::chrono::duration_cast<std::chrono::microseconds>(now - mStart)).count();
47 }
48};
49
50} // namespace netdutils
51} // namespace android
52
53#endif // NETDUTILS_STOPWATCH_H