• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 NETDUTILS_STOPWATCH_H
18 #define NETDUTILS_STOPWATCH_H
19 
20 #include <chrono>
21 
22 namespace android {
23 namespace netdutils {
24 
25 class Stopwatch {
26   private:
27     using clock = std::chrono::steady_clock;
28     using time_point = std::chrono::time_point<clock>;
29 
30   public:
Stopwatch()31     Stopwatch() : mStart(clock::now()) {}
32 
33     virtual ~Stopwatch() = default;
34 
timeTaken()35     float timeTaken() const { return getElapsed(clock::now()); }
36 
timeTakenUs()37     int64_t timeTakenUs() const { return getElapsedUs(clock::now()); }
38 
getTimeAndReset()39     float getTimeAndReset() {
40         const auto& now = clock::now();
41         float elapsed = getElapsed(now);
42         mStart = now;
43         return elapsed;
44     }
getTimeAndResetUs()45     float getTimeAndResetUs() {
46         const auto& now = clock::now();
47         float elapsed = getElapsedUs(now);
48         mStart = now;
49         return elapsed;
50     }
51 
52   private:
53     time_point mStart;
54 
getElapsed(const time_point & now)55     float getElapsed(const time_point& now) const {
56         using ms = std::chrono::duration<float, std::ratio<1, 1000>>;
57         return (std::chrono::duration_cast<ms>(now - mStart)).count();
58     }
getElapsedUs(const time_point & now)59     int64_t getElapsedUs(const time_point& now) const {
60         return (std::chrono::duration_cast<std::chrono::microseconds>(now - mStart)).count();
61     }
62 };
63 
64 }  // namespace netdutils
65 }  // namespace android
66 
67 #endif  // NETDUTILS_STOPWATCH_H
68