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