[flang] Accept polymorphic component element in storage_size
[llvm-project.git] / libc / src / time / linux / clock.cpp
blobd448f8ba54ed849625d1a50fbfe093abddf5a531
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 //===----------------------------------------------------------------------===//
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"
15 #include <errno.h>
16 #include <sys/syscall.h> // For syscall numbers.
17 #include <time.h>
19 namespace __llvm_libc {
21 LLVM_LIBC_FUNCTION(clock_t, clock, ()) {
22 struct timespec ts;
23 long ret_val = __llvm_libc::syscall_impl(
24 SYS_clock_gettime, CLOCK_PROCESS_CPUTIME_ID, reinterpret_cast<long>(&ts));
25 if (ret_val < 0) {
26 errno = -ret_val;
27 return clock_t(-1);
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)
37 return clock_t(-1);
38 if (ts.tv_nsec / 1000000000 > CLOCK_SECS_MAX - ts.tv_sec)
39 return clock_t(-1);
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