Austin Eng | ca0eac3 | 2019-08-28 23:18:10 +0000 | [diff] [blame] | 1 | // Copyright 2019 The Dawn Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | #include "utils/Timer.h" |
| 16 | |
| 17 | #include <stdint.h> |
| 18 | #include <time.h> |
| 19 | |
| 20 | namespace utils { |
| 21 | |
| 22 | namespace { |
| 23 | |
| 24 | uint64_t GetCurrentTimeNs() { |
| 25 | struct timespec currentTime; |
| 26 | clock_gettime(CLOCK_MONOTONIC, ¤tTime); |
| 27 | return currentTime.tv_sec * 1'000'000'000llu + currentTime.tv_nsec; |
| 28 | } |
| 29 | |
| 30 | } // anonymous namespace |
| 31 | |
| 32 | class PosixTimer : public Timer { |
| 33 | public: |
| 34 | PosixTimer() : Timer(), mRunning(false) { |
| 35 | } |
| 36 | |
| 37 | ~PosixTimer() override = default; |
| 38 | |
| 39 | void Start() override { |
| 40 | mStartTimeNs = GetCurrentTimeNs(); |
| 41 | mRunning = true; |
| 42 | } |
| 43 | |
| 44 | void Stop() override { |
| 45 | mStopTimeNs = GetCurrentTimeNs(); |
| 46 | mRunning = false; |
| 47 | } |
| 48 | |
| 49 | double GetElapsedTime() const override { |
| 50 | uint64_t endTimeNs; |
| 51 | if (mRunning) { |
| 52 | endTimeNs = GetCurrentTimeNs(); |
| 53 | } else { |
| 54 | endTimeNs = mStopTimeNs; |
| 55 | } |
| 56 | |
| 57 | return (endTimeNs - mStartTimeNs) * 1e-9; |
| 58 | } |
| 59 | |
| 60 | double GetAbsoluteTime() override { |
| 61 | return GetCurrentTimeNs() * 1e-9; |
| 62 | } |
| 63 | |
| 64 | private: |
| 65 | bool mRunning; |
| 66 | uint64_t mStartTimeNs; |
| 67 | uint64_t mStopTimeNs; |
| 68 | }; |
| 69 | |
| 70 | Timer* CreateTimer() { |
| 71 | return new PosixTimer(); |
| 72 | } |
| 73 | |
| 74 | } // namespace utils |