1//===-- Linux implementation of the clock function ------------------------===//
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 "src/time/clock.h"
10
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"
15#include "src/time/linux/clockGetTimeImpl.h"
16
17#include <sys/syscall.h> // For syscall numbers.
18#include <time.h>
19
20namespace LIBC_NAMESPACE {
21
22LLVM_LIBC_FUNCTION(clock_t, clock, ()) {
23 struct timespec ts;
24 auto result = internal::clock_gettimeimpl(CLOCK_PROCESS_CPUTIME_ID, ts: &ts);
25 if (!result.has_value()) {
26 libc_errno = result.error();
27 return -1;
28 }
29
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)
36 return clock_t(-1);
37 if (ts.tv_nsec / 1000000000 > CLOCK_SECS_MAX - ts.tv_sec)
38 return clock_t(-1);
39
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));
46}
47
48} // namespace LIBC_NAMESPACE
49

source code of libc/src/time/linux/clock.cpp