xref: /llvm-project/libc/test/src/time/clock_gettime_test.cpp (revision f9c2377fb68e5051b3061186c507f7b87db2a8b2)
1 //===-- Unittests for clock_gettime ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "hdr/time_macros.h"
10 #include "hdr/types/struct_timespec.h"
11 #include "hdr/types/time_t.h"
12 #include "src/__support/macros/properties/architectures.h"
13 #include "src/time/clock_gettime.h"
14 #include "test/UnitTest/Test.h"
15 
16 TEST(LlvmLibcClockGetTime, RealTime) {
17   timespec tp;
18   int result;
19   result = LIBC_NAMESPACE::clock_gettime(CLOCK_REALTIME, &tp);
20   // The GPU does not implement CLOCK_REALTIME but provides it so programs will
21   // compile.
22 #ifdef LIBC_TARGET_ARCH_IS_GPU
23   ASSERT_EQ(result, -1);
24 #else
25   ASSERT_EQ(result, 0);
26   ASSERT_GT(tp.tv_sec, time_t(0));
27 #endif
28 }
29 
30 #ifdef CLOCK_MONOTONIC
31 TEST(LlvmLibcClockGetTime, MonotonicTime) {
32   timespec tp1, tp2;
33   int result;
34   result = LIBC_NAMESPACE::clock_gettime(CLOCK_MONOTONIC, &tp1);
35   ASSERT_EQ(result, 0);
36   ASSERT_GT(tp1.tv_sec, time_t(0));
37   result = LIBC_NAMESPACE::clock_gettime(CLOCK_MONOTONIC, &tp2);
38   ASSERT_EQ(result, 0);
39   ASSERT_GE(tp2.tv_sec, tp1.tv_sec); // The monotonic clock should increase.
40   if (tp2.tv_sec == tp1.tv_sec) {
41     ASSERT_GE(tp2.tv_nsec, tp1.tv_nsec);
42   }
43 }
44 #endif // CLOCK_MONOTONIC
45