xref: /llvm-project/libcxx/src/filesystem/filesystem_clock.cpp (revision b69ddbc62838f23ace237c206676b1ed1c882638)
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 _LIBCPP_DIAGNOSTIC_PUSH
40 _LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Wdeprecated")
41 const bool _FilesystemClock::is_steady;
42 _LIBCPP_DIAGNOSTIC_POP
43 
44 _FilesystemClock::time_point _FilesystemClock::now() noexcept {
45   typedef chrono::duration<rep> __secs;
46 #if defined(_LIBCPP_WIN32API)
47   typedef chrono::duration<rep, nano> __nsecs;
48   FILETIME time;
49   GetSystemTimeAsFileTime(&time);
50   detail::TimeSpec tp = detail::filetime_to_timespec(time);
51   return time_point(__secs(tp.tv_sec) + chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
52 #elif defined(_LIBCPP_HAS_CLOCK_GETTIME)
53   typedef chrono::duration<rep, nano> __nsecs;
54   struct timespec tp;
55   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
56     __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
57   return time_point(__secs(tp.tv_sec) + chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
58 #else
59   typedef chrono::duration<rep, micro> __microsecs;
60   timeval tv;
61   gettimeofday(&tv, 0);
62   return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
63 #endif
64 }
65 
66 _LIBCPP_END_NAMESPACE_FILESYSTEM
67