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