blob: 9d3700e84889ef256777a2ad121a1e7a687c6d53 [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 {
23public:
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090024 Stopwatch() : mStart(clock::now()) {}
25
Robin Lee7e05cc92016-09-21 16:31:33 +090026 virtual ~Stopwatch() {};
27
28 float timeTaken() const {
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090029 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 Lee7e05cc92016-09-21 16:31:33 +090037 }
38
39private:
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090040 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 Lee7e05cc92016-09-21 16:31:33 +090048};
49
50#endif // NETD_INCLUDE_STOPWATCH_H