xref: /aosp_15_r20/external/llvm-libc/src/__support/time/linux/clock_conversion.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===--- clock conversion linux implementation ------------------*- C++ -*-===//
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 #ifndef LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_CLOCK_CONVERSION_H
10 #define LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_CLOCK_CONVERSION_H
11 
12 #include "src/__support/macros/config.h"
13 #include "src/__support/time/linux/clock_gettime.h"
14 #include "src/__support/time/units.h"
15 
16 namespace LIBC_NAMESPACE_DECL {
17 namespace internal {
18 
convert_clock(timespec input,clockid_t from,clockid_t to)19 LIBC_INLINE timespec convert_clock(timespec input, clockid_t from,
20                                    clockid_t to) {
21   using namespace time_units;
22   timespec from_time;
23   timespec to_time;
24   timespec output;
25   internal::clock_gettime(from, &from_time);
26   internal::clock_gettime(to, &to_time);
27   output.tv_sec = input.tv_sec - from_time.tv_sec + to_time.tv_sec;
28   output.tv_nsec = input.tv_nsec - from_time.tv_nsec + to_time.tv_nsec;
29 
30   if (output.tv_nsec > 1_s_ns) {
31     output.tv_sec++;
32     output.tv_nsec -= 1_s_ns;
33   } else if (output.tv_nsec < 0) {
34     output.tv_sec--;
35     output.tv_nsec += 1_s_ns;
36   }
37   return output;
38 }
39 
40 } // namespace internal
41 } // namespace LIBC_NAMESPACE_DECL
42 
43 #endif // LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_CLOCK_CONVERSION_H
44