brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.7 KiB · c560bd1 Raw
48 lines · cpp
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-exception6//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/libc_errno.h"14#include "src/__support/macros/config.h"15#include "src/__support/time/clock_gettime.h"16#include "src/__support/time/units.h"17 18namespace LIBC_NAMESPACE_DECL {19 20LLVM_LIBC_FUNCTION(clock_t, clock, ()) {21  using namespace time_units;22  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 represent31  // 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 work40  // 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_DECL48