1 //===-- Linux implementation of the clock function ------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/time/clock.h"
11 #include "src/__support/CPP/limits.h"
12 #include "src/__support/OSUtil/syscall.h" // For internal syscall function.
13 #include "src/__support/common.h"
14 #include "src/errno/libc_errno.h"
16 #include <sys/syscall.h> // For syscall numbers.
19 namespace __llvm_libc
{
21 LLVM_LIBC_FUNCTION(clock_t, clock
, ()) {
23 long ret_val
= __llvm_libc::syscall_impl(
24 SYS_clock_gettime
, CLOCK_PROCESS_CPUTIME_ID
, reinterpret_cast<long>(&ts
));
26 libc_errno
= -ret_val
;
30 // The above syscall gets the CPU time in seconds plus nanoseconds.
31 // The standard requires that we return clock_t(-1) if we cannot represent
32 // clocks as a clock_t value.
33 constexpr clock_t CLOCK_SECS_MAX
=
34 cpp::numeric_limits
<clock_t>::max() / CLOCKS_PER_SEC
;
35 if (ts
.tv_sec
> CLOCK_SECS_MAX
)
37 if (ts
.tv_nsec
/ 1000000000 > CLOCK_SECS_MAX
- ts
.tv_sec
)
40 // For the integer computation converting tv_nsec to clocks to work
41 // correctly, we want CLOCKS_PER_SEC to be less than 1000000000.
42 static_assert(1000000000 > CLOCKS_PER_SEC
,
43 "Expected CLOCKS_PER_SEC to be less than 1000000000.");
44 return clock_t(ts
.tv_sec
* CLOCKS_PER_SEC
+
45 ts
.tv_nsec
/ (1000000000 / CLOCKS_PER_SEC
));
48 } // namespace __llvm_libc