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"
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
));
30 // The above syscall gets the CPU time in seconds plus nanoseconds. We should
31 // make sure that corresponding clocks can actually be represented by clock-t.
32 // The standard requires that we return clock_t(-1) if we cannot represent
33 // clocks as a clock_t value.
34 constexpr clock_t CLOCK_SECS_MAX
=
35 cpp::numeric_limits
<clock_t>::max() / CLOCKS_PER_SEC
;
36 if (ts
.tv_sec
> CLOCK_SECS_MAX
)
38 if (ts
.tv_nsec
/ 1000000000 > CLOCK_SECS_MAX
- ts
.tv_sec
)
41 // For the integer computation converting tv_nsec to clocks to work
42 // correctly, we want CLOCKS_PER_SEC to be less than 1000000000.
43 static_assert(1000000000 > CLOCKS_PER_SEC
,
44 "Expected CLOCKS_PER_SEC to be less than 1000000000.");
45 return clock_t(ts
.tv_sec
* CLOCKS_PER_SEC
+
46 ts
.tv_nsec
/ (1000000000 / CLOCKS_PER_SEC
));
49 } // namespace __llvm_libc