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 #include "hdr/time_macros.h" 11 #include "src/__support/CPP/limits.h" 12 #include "src/__support/common.h" 13 #include "src/__support/macros/config.h" 14 #include "src/__support/time/linux/clock_gettime.h" 15 #include "src/__support/time/units.h" 16 #include "src/errno/libc_errno.h" 17 18 namespace LIBC_NAMESPACE_DECL { 19 20 LLVM_LIBC_FUNCTION(clock_t, clock, ()) { 21 using namespace time_units; 22 struct timespec ts; 23 auto result = internal::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); 24 if (!result.has_value()) { 25 libc_errno = result.error(); 26 return -1; 27 } 28 29 // The above syscall gets the CPU time in seconds plus nanoseconds. 30 // The standard requires that we return clock_t(-1) if we cannot represent 31 // clocks as a clock_t value. 32 constexpr clock_t CLOCK_SECS_MAX = 33 cpp::numeric_limits<clock_t>::max() / CLOCKS_PER_SEC; 34 if (ts.tv_sec > CLOCK_SECS_MAX) 35 return clock_t(-1); 36 if (ts.tv_nsec / 1_s_ns > CLOCK_SECS_MAX - ts.tv_sec) 37 return clock_t(-1); 38 39 // For the integer computation converting tv_nsec to clocks to work 40 // correctly, we want CLOCKS_PER_SEC to be less than 1000000000. 41 static_assert(1_s_ns > CLOCKS_PER_SEC, 42 "Expected CLOCKS_PER_SEC to be less than 1'000'000'000."); 43 return clock_t(ts.tv_sec * CLOCKS_PER_SEC + 44 ts.tv_nsec / (1_s_ns / CLOCKS_PER_SEC)); 45 } 46 47 } // namespace LIBC_NAMESPACE_DECL 48