83ecc0c23a6c1db3baeb2e6b62353e1e5662574e
[folly.git] / folly / portability / test / TimeTest.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
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 #include <folly/portability/Time.h>
18
19 #include <folly/test/TestUtils.h>
20
21 #include <chrono>
22
23 #include <gtest/gtest.h>
24
25 static constexpr auto kAcceptableDeltaSecs = std::chrono::seconds(120);
26
27 using folly::test::AreWithinSecs;
28
29 #ifdef CLOCK_REALTIME
30
31 TEST(Time, clockGettimeRealtimeAreWithin120SecsOfStdChronoSystemClock) {
32   struct timespec ts;
33   auto ret = clock_gettime(CLOCK_REALTIME, &ts);
34   ASSERT_EQ(0, ret);
35
36   auto gettimeResult =
37       std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec);
38   auto stdChronoSystemClockNow =
39       std::chrono::system_clock::now().time_since_epoch();
40   ASSERT_TRUE(AreWithinSecs(
41       gettimeResult, stdChronoSystemClockNow, kAcceptableDeltaSecs));
42 }
43
44 #endif /* CLOCK_REALTIME */
45
46 #ifdef CLOCK_MONOTONIC
47
48 TEST(Time, clockGettimeMonotonicAreWithin120SecsOfStdChronoSteadyClock) {
49   struct timespec ts;
50   auto ret = clock_gettime(CLOCK_MONOTONIC, &ts);
51   ASSERT_EQ(0, ret);
52
53   auto gettimeResult =
54       std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec);
55   auto stdChronoSteadyClockNow =
56       std::chrono::steady_clock::now().time_since_epoch();
57   ASSERT_TRUE(AreWithinSecs(
58       gettimeResult, stdChronoSteadyClockNow, kAcceptableDeltaSecs));
59 }
60
61 #endif /* CLOCK_MONOTONIC */
62
63 #ifdef CLOCK_PROCESS_CPUTIME_ID
64
65 TEST(Time, clockGettimeProcessCputimeIsGreaterThanZero) {
66   struct timespec ts;
67   auto ret = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
68   ASSERT_EQ(0, ret);
69
70   auto gettimeResult =
71       std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec);
72
73   ASSERT_GT(gettimeResult, std::chrono::nanoseconds::zero());
74 }
75
76 #endif /* CLOCK_PROCESS_CPUTIME_ID */
77
78 #ifdef CLOCK_THREAD_CPUTIME_ID
79
80 TEST(Time, clockGettimeProcessThreadTimeIsGreaterThanZero) {
81   struct timespec ts;
82   auto ret = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
83   ASSERT_EQ(0, ret);
84
85   auto gettimeResult =
86       std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec);
87
88   ASSERT_GT(gettimeResult, std::chrono::nanoseconds::zero());
89 }
90
91 #endif /* CLOCK_THREAD_CPUTIME_ID */