xref: /llvm-project/libcxx/src/filesystem/filesystem_clock.cpp (revision 0eb1fc88680e2df430a5cb68be5e6a671b43c82d)
1 //===----------------------------------------------------------------------===//
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 <__config>
10 #include <chrono>
11 #include <filesystem>
12 #include <time.h>
13 
14 #if defined(_LIBCPP_WIN32API)
15 #  include "time_utils.h"
16 #endif
17 
18 #if defined(_LIBCPP_WIN32API)
19 #  define WIN32_LEAN_AND_MEAN
20 #  define NOMINMAX
21 #  include <windows.h>
22 #endif
23 
24 #if __has_include(<unistd.h>)
25 #  include <unistd.h> // _POSIX_TIMERS
26 #endif
27 
28 #if __has_include(<sys/time.h>)
29 #  include <sys/time.h> // for gettimeofday and timeval
30 #endif
31 
32 #if defined(__APPLE__) || defined(__gnu_hurd__) || defined(__AMDGPU__) || defined(__NVPTX__) ||                        \
33     (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0)
34 #  define _LIBCPP_HAS_CLOCK_GETTIME
35 #endif
36 
37 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
38 
39 const bool _FilesystemClock::is_steady;
40 
41 _FilesystemClock::time_point _FilesystemClock::now() noexcept {
42   typedef chrono::duration<rep> __secs;
43 #if defined(_LIBCPP_WIN32API)
44   typedef chrono::duration<rep, nano> __nsecs;
45   FILETIME time;
46   GetSystemTimeAsFileTime(&time);
47   detail::TimeSpec tp = detail::filetime_to_timespec(time);
48   return time_point(__secs(tp.tv_sec) + chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
49 #elif defined(_LIBCPP_HAS_CLOCK_GETTIME)
50   typedef chrono::duration<rep, nano> __nsecs;
51   struct timespec tp;
52   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
53     __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
54   return time_point(__secs(tp.tv_sec) + chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
55 #else
56   typedef chrono::duration<rep, micro> __microsecs;
57   timeval tv;
58   gettimeofday(&tv, 0);
59   return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
60 #endif
61 }
62 
63 _LIBCPP_END_NAMESPACE_FILESYSTEM
64