1/* Copyright 2019 Google LLC. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#ifndef RUY_RUY_TIME_H_
17#define RUY_RUY_TIME_H_
18
19#include <chrono> // NOLINT(build/c++11)
20#include <cstdint> // IWYU pragma: keep
21#include <ratio> // NOLINT(build/c++11)
22
23#ifdef __linux__
24#include <sys/time.h>
25// IWYU pragma: no_include <type_traits>
26
27#include <ctime>
28#endif
29
30namespace ruy {
31
32using InternalDefaultClock = std::chrono::steady_clock;
33
34using TimePoint = InternalDefaultClock::time_point;
35using Duration = InternalDefaultClock::duration;
36
37template <typename RepresentationType>
38Duration DurationFromSeconds(RepresentationType representation) {
39 return std::chrono::duration_cast<Duration>(
40 std::chrono::duration<RepresentationType>(representation));
41}
42
43template <typename RepresentationType>
44Duration DurationFromMilliseconds(RepresentationType representation) {
45 return std::chrono::duration_cast<Duration>(
46 std::chrono::duration<RepresentationType, std::milli>(representation));
47}
48
49template <typename RepresentationType>
50Duration DurationFromNanoseconds(RepresentationType representation) {
51 return std::chrono::duration_cast<Duration>(
52 std::chrono::duration<RepresentationType, std::nano>(representation));
53}
54
55inline float ToFloatSeconds(const Duration& duration) {
56 return std::chrono::duration_cast<std::chrono::duration<float>>(duration)
57 .count();
58}
59
60inline float ToFloatMilliseconds(const Duration& duration) {
61 return std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(
62 duration)
63 .count();
64}
65
66inline std::int64_t ToInt64Nanoseconds(const Duration& duration) {
67 return std::chrono::duration_cast<
68 std::chrono::duration<std::int64_t, std::nano>>(duration)
69 .count();
70}
71
72inline TimePoint Now() { return InternalDefaultClock::now(); }
73
74inline TimePoint CoarseNow() {
75#ifdef __linux__
76 timespec t;
77 clock_gettime(CLOCK_MONOTONIC_COARSE, &t);
78 return TimePoint(
79 DurationFromNanoseconds(1000000000LL * t.tv_sec + t.tv_nsec));
80#else
81 return Now();
82#endif
83}
84
85} // namespace ruy
86
87#endif // RUY_RUY_TIME_H_
88